我正在创建一个时间应用程序,用于计算当前时间和自1970年1月1日午夜以来经过的时间(以毫秒为单位)。我继续使用Calendar并且能够成功返回当前时间,但由于某种原因,经过的时间返回0.不确定为什么会这样。
这是我目前的代码:
import java.util.Calendar;
import java.util.TimeZone;
public class TimeApp {
public static void main(String[] args) {
Time time1 = new Time();
System.out.println("Hour: " + time1.getHour() + " Minute: " +
time1.getMinute() + " Second: " + time1.getSecond());
Time time2 = new Time();
System.out.println("Elapsed time since epoch: " + time2.getElapsedTime());
}
}
final class Time {
private int hour;
private int minute;
private int second;
private long secondsSinceEpoch;
public Time() {
Calendar calendar = Calendar.getInstance();
this.second = calendar.get(Calendar.SECOND);
this.minute = calendar.get(Calendar.MINUTE);
this.hour = calendar.get(Calendar.HOUR_OF_DAY);
}
public Time(long elapsedTime) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.clear();
calendar.set(2016, Calendar.SEPTEMBER, 9);
secondsSinceEpoch = calendar.getTimeInMillis() / 1000L;
}
@Override
public String toString() {
return hour + ":" + minute + ":" + second;
}
public int getHour() {
return hour;
}
public int getMinute() {
return minute;
}
public int getSecond() {
return second;
}
public long getElapsedTime() {
return secondsSinceEpoch;
}
}
答案 0 :(得分:0)
You aren't setting elapsedTime
for time2
. I think you wanted
Time time2 = new Time(System.currentTimeMillis());
And as pointed out in the comments, you aren't using elapsedTime
in your constructor. Something like
public Time(long elapsedTime) {
secondsSinceEpoch = elapsedTime / 1000;
}
答案 1 :(得分:0)
我认为您使用了time2
的错误构造函数,因为您调用了Time()
并且此版本未设置secondsSinceEpoch
。尝试使用具有任何长值的其他构造函数Time(long elapsedTime)
,看看它是否有效。
像这样......
Time time2 = new Time(10000);
然后重新编写此构造函数,因为您从不使用elapsedTime
,或者完全删除它并重新编写第一个构造函数以将值赋给secondsSinceEpoch
。
public Time() {
Calendar calendar = Calendar.getInstance();
this.second = calendar.get(Calendar.SECOND);
this.minute = calendar.get(Calendar.MINUTE);
this.hour = calendar.get(Calendar.HOUR_OF_DAY);
secondsSinceEpoch = calendar.getTimeInMillis() / 1000L;
}