Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a 1 day difference in these dates?

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?

like image 303
Old Nick Avatar asked May 31 '17 10:05

Old Nick


1 Answers

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.

like image 188
tzaman Avatar answered Nov 10 '22 14:11

tzaman