Why is there a 1 day difference on these dates?

I am experimenting with DateFormat, and I ran into a problem when I create a date, saving it as a string, and then parse it back to a date and somehow ending with the same date, but on 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 the number of minutes in milliseconds is less than when the date is parsed, this will work as I would expect if the parsing day coincided with the start day.

Not sure what is going on, can anyone explain this?

+5
source share
1 answer

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

September 27 - Saturday in 1958, but on Friday at 33658. With fewer milliseconds in d1 you create realistic years, so the discrepancy does not occur.

You will need to use the more complete DateFormat option if you do not want to lose information.

+12
source

Source: https://habr.com/ru/post/1268391/


All Articles