In the question A very strange date before 1970, I know the reason why two times looks only have difference of 1s, but sometimes we can get another value.
For example from that question:
public static void main(String[] args) throws ParseException {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str3 = "1927-12-31 23:54:07";
String str4 = "1927-12-31 23:54:08";
Date sDt3 = sf.parse(str3);
Date sDt4 = sf.parse(str4);
long ld3 = sDt3.getTime() /1000;
long ld4 = sDt4.getTime() /1000;
System.out.println(ld4-ld3);
}
The output will be 353 in a timezone of Shanghai, but will be 1 in other timezones.
My question is, how to calculate the difference without timezones? How to always get the correct difference?
You can easily handle timezones with Joda Time.
You can create a DateTimeFormatter with the desired time zone and use it to parse the string. The DateTime instances can also be converted to other time zones.
You can ignore timezones completely by using the LocalDateTime class.
Also the Period class has methods like toStandardSeconds(), toStandardDuration(), normalizedStandard() etc. which “makes the assumption that all weeks are 7 days, all days are 24 hours, all hours are 60 minutes and all minutes are 60 seconds. This is not true when daylight savings time is considered, and may also not be true for some unusual chronologies. However, it is included as it is a useful operation for many applications and business rules.”
Here is how to construct a timezoneless LocalDateTime either directly or by conversion from a timezoneful DateTime instance.
This will print as follows. Notice the funny timezone in Shanghai time before its timezone adjustment in 1927.