Why is there a 1 day difference in these dates?
Asked Answered
I

1

5

I am experimenting with DateFormat and I've come across an issue where I'm creating a date, storing it as a string and then parsing it back into a date and somehow ending up with the same date but a different day of the week.

import java.text.*;
import java.util.*;
public class Dates {

    public static void main (String [] args) {
        Date d1 = new Date(1000000000000000L);
        System.out.println("d1 = " + d1.toString());        
        DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);       
        String s = df.format(d1);
        System.out.println(s);      
        try {           
            Date d2= df.parse(s);
            System.out.println( "Parsed Date = " + d2.toString());          
        } catch (ParseException e) {            
            System.out.println("Parse Exception");          
        }       
    }       
}

I get the output;

d1 = Fri Sep 27 02:46:40 BST 33658
27/09/58
Parsed Date = Sat Sep 27 00:00:00 BST 1958

If I make the number of milliseconds in d1 smaller then when the date is parsed back it works the way I'd expect with the parsed day matching the initial day.

Not sure what's going on, can anyone explain it?

Iow answered 31/5, 2017 at 10:47 Comment(3)
Did you also notice that the year is completely different?Spherule
No I hadn't noticed that Oliver, thanks.Iow
I recommend you make explicit in which time zone you want to format and parse the date (even if it’s TimeZone.getDefault()). And I recommend you switch to using the modern date and time classes, like Instant, LocalDate, DateTimeFormatter and ZoneId.Unbeaten
M
12

The original year 33658 is getting shortened to '58' when you store it as a string, and then (reasonably) getting interpreted as 1958 instead when you read it back.

Sep 27 is a Saturday in 1958, but a Friday in 33658. With a smaller number of milliseconds in d1 you're creating realistic years, so the mismatch doesn't happen.

You'll need to use a more complete DateFormat option if you don't want to lose information.

Mihrab answered 31/5, 2017 at 10:54 Comment(1)
Thanks, I just tried it with DateFormat.LONG and it worked properly.Iow

© 2022 - 2024 — McMap. All rights reserved.