Java – how to calculate next week?

I want to accurately calculate the time of a week on a given date, but the output I get is an hour earlier

Code:

long DURATION = 7 * 24 * 60 * 60 * 1000;
System.out.println("    Now: " + new Date(System.currentTimeMillis()));
System.out.println("next week: " + new Date(System.currentTimeMillis() + DURATION));

Output:

Now: Wed Sep 16 09:52:36 IRDT 2015
next week: Wed Sep 23 08:52:36 IRST 2015

How to calculate correctly?

Solution

Never rely on millisecond arithmetic. There are too many rules and traps to make it any value (even in a short period of time), but use special libraries, such as Java 8's time API, jodatime and even calendar

Java 8

LocalDateTime Now = LocalDateTime.Now();
LocalDateTime then = Now.plusDays(7);

System.out.println(Now);
System.out.println(then);

Which outputs

2015-09-16T15:34:14.771
2015-09-23T15:34:14.771

JodaTime

LocalDateTime Now = LocalDateTime.Now();
LocalDateTime then = Now.plusDays(7);

System.out.println(Now);
System.out.println(then);

Which outputs

2015-09-16T15:35:19.954
2015-09-23T15:35:19.954

calendar

When you cannot use Java 8 or jodatime

Calendar cal = Calendar.getInstance();
Date Now = cal.getTime();
cal.add(Calendar.DATE,7);
Date then = cal.getTime();

System.out.println(Now);
System.out.println(then);

Which outputs

Wed Sep 16 15:36:39 EST 2015
Wed Sep 23 15:36:39 EST 2015

NB: the "problem" you seem to be having is not a problem at all, but just during this time, your time zone seems to have entered / exited the light saving of the day, so date is displaying the time, which is the correct offset

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>