-2

I have the following Java code that takes a date and should add a full day to the date:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateString = "2017-01-30T19:00:00+0000"
Date date = formatter.parse(dateString);

long timeBetweenStartDates = 24 * 60 * 1000;
Long DateWithOneDayAddedInMilis = date.getTime()+timeBetweenStartDates;
Date dateWithOneDayAdded = new Date((DateWithOneDayAddedInMilis));

The value I am getting for dateWithOneDayAdded is:

Mon Jan 30 13:24:00 GMT 2017

What I am looking for here would be:

 Tue Jan 31 13:24:00 GMT 2017

How can I ensure that the date is in the format I expect?

java123999
  • 6,974
  • 36
  • 77
  • 121
  • 1
    Why would you expect a whole day to be added? You've only added 24 minutes. 1000 milliseconds = 1 second. 60 * 1000 milliseconds = 1 minute. 24 * 60 * 1000 milliseconds = 24 minutes. – Jon Skeet May 19 '17 at 10:23
  • long timeBetweenStartDates = 24 * 60 * 60* 1000; – Adam May 19 '17 at 10:29
  • I think you meant you expected `Tue Jan 31 13:00:00 (your time zone here) 2017` without the 24, not `Tue Jan 31 13:24:00 GMT 2017`. – Ole V.V. May 19 '17 at 12:00

1 Answers1

1

Oh, what a wonderful example of where the newer date and time classes are much more programmer-friendly. With these it’s next to impossible to make an error like the one you made (and which is pretty easy to make with the old classes, and in particular, very hard to spot once you have written the code).

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
    String dateString = "2017-01-30T19:00:00+0000";
    OffsetDateTime dateTime = OffsetDateTime.parse(dateString, formatter);
    OffsetDateTime dateWithOneDayAdded = dateTime.plusDays(1);
    System.out.println(dateWithOneDayAdded);

This prints

2017-01-31T19:00Z

You may of course format the calculated date-time the way you or your users prefer.

An added benefit is that plusDays() handles transistion to and from summer time (DST) nicely and hits the same time on the next day (if possible) rather than blindly adding 24 hours.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • Not sure, but I think I read that with this particular format with Java 9 you may use just `OffsetDateTime.parse(dateString)` without using the formatter. – Ole V.V. May 20 '17 at 13:10