英文:
Java Date toInstant method return a different date?
问题
以下是翻译好的部分:
这是我的测试代码,日期为 1111-11-11
到 instant
方法的结果是 1111-11-17
jshell> new Date(-789,10,11)
$8 ==> Sat Nov 11 00:00:00 JST 1111
jshell> new Date(-789,10,11).toInstant();
$9 ==> 1111-11-17T15:00:00Z
英文:
Here is my test code, date of 1111-11-11
to instant method result is 1111-11-17
jshell> new Date(-789,10,11)
$8 ==> Sat Nov 11 00:00:00 JST 1111
jshell> new Date(-789,10,11).toInstant();
$9 ==> 1111-11-17T15:00:00Z
答案1
得分: 2
我建议您从过时且容易出错的旧日期时间API切换到现代日期时间API。
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
public class Main {
public static void main(String args[]) {
OffsetDateTime odt = OffsetDateTime.of(1111, 11, 11, 0, 0, 0, 0, ZoneOffset.UTC);
Instant instant = odt.toInstant();
System.out.println(instant);
}
}
输出:
1111-11-11T00:00:00Z
如何使用旧日期时间API进行操作:
请注意,1582-10-15
之前的日期将被视为朱利安历。查看更多详情,请访问 https://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html。还请查看 https://stackoverflow.com/a/23460471/10819573,我在编写以下代码时参考了该链接:
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class Main {
public static void main(String args[]) throws ParseException {
GregorianCalendar proleptic = new GregorianCalendar();
proleptic.clear();
proleptic.setGregorianChange(new Date(Long.MIN_VALUE));
proleptic.set(Calendar.DAY_OF_MONTH, 11);
proleptic.set(Calendar.MONTH, Calendar.NOVEMBER);
proleptic.set(Calendar.YEAR, 1111);
System.out.println(proleptic.toInstant());
}
}
输出:
1111-11-11T00:00:00Z
英文:
I recommend you switch from the outdated and error-prone legacy date-time API to the modern date-time API.
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
public class Main {
public static void main(String args[]) {
OffsetDateTime odt = OffsetDateTime.of(1111, 11, 11, 0, 0, 0, 0, ZoneOffset.UTC);
Instant instant = odt.toInstant();
System.out.println(instant);
}
}
Output:
1111-11-11T00:00:00Z
How to do it using the legacy date-time API:
Note that the dates before 1582-10-15
are handled as Julian calendar. Check https://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html for more details. Please also check https://stackoverflow.com/a/23460471/10819573 which I've referred to write the following code:
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class Main {
public static void main(String args[]) throws ParseException {
GregorianCalendar proleptic = new GregorianCalendar();
proleptic.clear();
proleptic.setGregorianChange(new Date(Long.MIN_VALUE));
proleptic.set(Calendar.DAY_OF_MONTH, 11);
proleptic.set(Calendar.MONTH, Calendar.NOVEMBER);
proleptic.set(Calendar.YEAR, 1111);
System.out.println(proleptic.toInstant());
}
}
Output:
1111-11-11T00:00:00Z
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论