gpt4 book ai didi

java - 时代困惑,需要澄清

转载 作者:行者123 更新时间:2023-11-30 06:27:42 24 4
gpt4 key购买 nike

给定:

private Calendar calendarInstance = Calendar.getInstance();

public long inMillis() {
calendarInstance.set(year, month, day, hour, min);
return calendarInstance.getTimeInMillis();
}

据我了解,结果返回自纪元以来的时间,以毫秒为单位

The current time as UTC milliseconds from the epoch.

既然我的测试总是设置相同的对象,为什么随着时间的推移结果会不同?

detailedMoment = new MomentInTime(2012, 11, 1, 19, 9);
detailedMoment.inMillis() // gives different results as time passes by

更新:

由于以下原因,我继续猜测自己 enter image description here

在同一时间我得到

1_351_796_940 // http://www.epochconverter.com
1_354_410_540 // my number

最佳答案

我认为你应该使用 clear() .如果您这样做,它每次都会返回准确的毫秒数。

public long inMillis() {
calendarInstance.clear();
calendarInstance.set(year, month, day, hour, min);
return calendarInstance.getTimeInMillis();
}

来自 Java 文档

Sets all the calendar field values and the time value (millisecond offset from the Epoch) of this Calendar undefined. This means that isSet() will return false for all the calendar fields, and the date and time calculations will treat the fields as if they had never been set. A Calendar implementation class may use its specific default field values for date/time calculations. For example, GregorianCalendar uses 1970 if the YEAR field value is undefined.

示例程序

public class MomentInTime {

private static Calendar calendarInstance = Calendar.getInstance();

public static long inMillis() {
calendarInstance.clear();
calendarInstance.set(2012, 10, 1, 19, 9);
return calendarInstance.getTimeInMillis();
}

public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 10; i++) {
System.out.println(inMillis()/1000);
Thread.sleep(300);
}
}
}

输出:

 1351777140

enter image description here

关于java - 时代困惑,需要澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13184508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com