Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate next week?

Tags:

java

time

I want to precisely calculate the time one week from a given date, but the output I get back is one hour early.

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 can I calculate this correctly?

like image 926
Askar Avatar asked Sep 16 '15 05:09

Askar


People also ask

How do I calculate next week in Excel?

=date + 7 – WEEKDAY(date + 7 –dow) Where; Date- this shows the date that excel is expected to start counting from.

How do you calculate per week?

(Based on 365 days in a year, 7 days in a week: 365 divided by 7 = 52.14). This figure can be used as a basis for calculations as above and result in slightly different amounts.

How do I calculate the next day in Excel?

To get the next working day, or next business day, you can use the WORKDAY function. The WORKDAY formula is fully automatic. Given a date and days, it will add days to the date, taking into account weekends and, optionally, holidays.


1 Answers

Never, ever rely on millisecond arithmetic, there are too many rules and gotchas to make it of any worth (even over a small span of time), instead use a dedicated library, like Java 8's Time API, JodaTime or 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 can't 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, isn't a problem at all, but simply the fact that over the period, your time zone seems to have entered/exited day light savings, so Date is displaying the time, with it's correct offset

like image 157
MadProgrammer Avatar answered Sep 16 '22 11:09

MadProgrammer