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?
TimeZone.getDefault()
). And I recommend you switch to using the modern date and time classes, likeInstant
,LocalDate
,DateTimeFormatter
andZoneId
. – Unbeaten