我想在Java中减去两个日期(一个是常量,一个是当前日期),但是我遇到了奇怪的问题。代码如下:
DateFormat df = new SimpleDateFormat("HH:MM");
Date FirstLessonInterval=df.parse("08:45");
Date currentTime = new Date();
long diff = FirstLessonInterval.getTime()-currentTime.getTime();
String s = String.valueOf(diff);
LessonOrBreak=(diff);我只剩几分钟了。当我想用FirstLessonInterval.toString()查看FirstLessonInterval时,它显示的是1970年。我能做什么?
发布于 2014-05-11 22:33:30
你忘了给出日期,你只是定义了一个时间:
DateFormat df = new SimpleDateFormat("HH:MM");
Date FirstLessonInterval=df.parse("08:45");这是unix time的第0天,也就是1.1.1970
试试像这样的东西
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:MM");
Date FirstLessonInterval=df.parse("2014/05/10 08:45");发布于 2014-05-11 22:32:57
根据计算机的说法,所有的时间都始于1970年。我们在你的问题中遗漏了一些代码吗?你可以用毫秒来表示当前时间,但我会先看看JodaTime,然后再用它。
你得到1970年的原因是……是因为我怀疑你的差值是相当小的。然后,如果你把它看作一个日期,那么它将是一个小数字+1970年1月1日,它仍然是1970年。但正如我所说的,我怀疑你的问题中缺少一些代码。
在JodaTime中,你可以像下面这样做,但是我不确定你到底想要什么
Interval i= new Interval(new DateTime(FirstLessonInterval), new DateTime());
System.out.println("Interval is: " + i.toDurationMillis());发布于 2014-05-11 22:46:45
mm来表示分钟紧跟你的原始代码;
DateFormat df = new SimpleDateFormat("HH:mm");
Date firstLessonInterval = df.parse("08:45");
Date currentTime = new Date();
// Format the current date comparable to UNIX epoch (only hold time params)
String dateStr = df.format(currentTime.getTime());
// Parse the modified date string to a date object
Date comDate = df.parse(dateStr);
// Take the difference in millis
long diff = firstLessonInterval.getTime() - comDate.getTime();
String s = String.valueOf(diff);
// Print the number of minutes passed since
System.out.println("Minutes {elapsed since/time to} 08:45 - " + Math.abs(diff) / 1000 / 60);https://stackoverflow.com/questions/23593697
复制相似问题