Why is subtracting these two times (in 1927) giving a strange result?

Multi tool use
Multi tool use


Why is subtracting these two times (in 1927) giving a strange result?



If I run the following program, which parses two date strings referencing times 1 second apart and compares them:


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 is:



353



Why is ld4-ld3 not 1 (as I would expect from the one-second difference in the times), but 353?


ld4-ld3


1


353



If I change the dates to times 1 second later:


String str3 = "1927-12-31 23:54:08";
String str4 = "1927-12-31 23:54:09";



Then ld4-ld3 will be 1.


ld4-ld3


1



Java version:


java version "1.6.0_22"
Java(TM) SE Runtime Environment (build 1.6.0_22-b04)
Dynamic Code Evolution Client VM (build 0.2-b02-internal, 19.0-b04-internal, mixed mode)

Timezone(`TimeZone.getDefault()`):

sun.util.calendar.ZoneInfo[id="Asia/Shanghai",
offset=28800000,dstSavings=0,
useDaylight=false,
transitions=19,
lastRule=null]

Locale(Locale.getDefault()): zh_CN





Did you really stumble upon that exact situation in a real-life scenario or was this question only meant to be a puzzler -- just for the fun of it ?
– Costi Ciudatu
Jul 27 '11 at 8:42





@Costi Ciudatu: FWIW, I could easily imagine this coming up as the result of reducing a larger bug -- i.e., "Why are these two dates a year apart not exactly a year apart?"
– Brooks Moses
Jul 30 '11 at 1:43





The real answer is to always, always use seconds since an epoch for logging, like the Unix epoch, with 64 bit integer representation (signed, if you want to allow stamps before the epoch). Any real-world time system has some non-linear, non-monotonic behaviour like leap hours or daylight savings.
– Phil H
Jul 12 '12 at 8:34





originally posted as Oracle Bug ID 7070044 on Jul 23 `11
– Arno
Aug 4 '12 at 10:55






As @Costi Ciudatu , I really wonder from which bug report did the OP dig this one up. I'm also pretty sure except for being a puzzle this is not useful to 99.9(add lots of 9 digits) percent of users. He does get the medal for the reputation "game".
– Menelaos Bakopoulos
Oct 11 '13 at 10:32





8 Answers
8



It's a time zone change on December 31st in Shanghai.



See this page for details of 1927 in Shanghai. Basically at midnight at the end of 1927, the clocks went back 5 minutes and 52 seconds. So "1927-12-31 23:54:08" actually happened twice, and it looks like Java is parsing it as the later possible instant for that local date/time - hence the difference.



Just another episode in the often weird and wonderful world of time zones.



EDIT: Stop press! History changes...



The original question would no longer demonstrate quite the same behaviour, if rebuilt with version 2013a of TZDB. In 2013a, the result would be 358 seconds, with a transition time of 23:54:03 instead of 23:54:08.



I only noticed this because I'm collecting questions like this in Noda Time, in the form of unit tests... The test has now been changed, but it just goes to show - not even historical data is safe.



EDIT: History has changed again...



In TZDB 2014f, the time of the change has moved to 1900-12-31, and it's now a mere 343 second change (so the time between t and t+1 is 344 seconds, if you see what I mean).


t


t+1



EDIT: To answer a question around a transition at 1900... it looks like the Java timezone implementation treats all time zones as simply being in their standard time for any instant before the start of 1900 UTC:


import java.util.TimeZone;

public class Test {
public static void main(String args) throws Exception {
long startOf1900Utc = -2208988800000L;
for (String id : TimeZone.getAvailableIDs()) {
TimeZone zone = TimeZone.getTimeZone(id);
if (zone.getRawOffset() != zone.getOffset(startOf1900Utc - 1)) {
System.out.println(id);
}
}
}
}



The code above produces no output on my Windows machine. So any time zone which has any offset other than its standard one at the start of 1900 will count that as a transition. TZDB itself has some data going back earlier than that, and doesn't rely on any idea of a "fixed" standard time (which is what getRawOffset assumes to be a valid concept) so other libraries needn't introduce this artificial transition.


getRawOffset





@Gareth: Nope, but checking the details of Shanghai time zone transitions at that period was my first port of call. And I've been working on time zone transitions for Noda Time recently, so the possibility of ambiguity is pretty much at the forefront of my thoughts anyway...
– Jon Skeet
Jul 27 '11 at 8:35





@Johannes: To make it a more globally normal time zone, I believe - the resulting offset is UTC+8. Paris did the same sort of thing in 1911 for example: timeanddate.com/worldclock/clockchange.html?n=195&year=1911
– Jon Skeet
Jul 27 '11 at 13:25






@Charles: back then, travellers knew to expect local time to be different everywhere (because it was). Additionally, watches were mechanical and drifted quickly, so people we used to adjusting them according to the local clocktower every couple of days anyway, even if they did not travel. So how were the tower clocks (which also drifted) set? Most easily by setting them to 12:00 when the sun reached its daily peak... which was different in every place not on the same longitude. This was the norm pretty much everywhere until railroad timetables required some sort of standardization.
– Michael Borgwardt
Jul 28 '11 at 12:58





But then : how on Earth has this kind of knowledge survived the ages, so that nearly a century ago, it is implemented in software ? In 2011, anyone who mention timezone oddities to a non-software engineer is looked upon like a nerd. (And really, people expect all software to abstract it, and they don't give a damn if it's ambigous, when they say 'noon', we software engineer should deal with it). But to imagine someone in Shangai, in December 1927, thinking it would be relevant to note such a thing down, and that somehow this information was never lost, deleted, anything ... mind's blown.
– phtrivier
Jul 30 '11 at 16:28





@EdS. It actually only took him 15 minutes, the reason it shows a 16 minute difference is due to a slight timezone discrepancy on July 27th 2011 caused by how awesome Jon Skeet is.
– JessieArr
Oct 18 '13 at 16:37




You've encountered a local time discontinuity:



When local standard time was about to reach Sunday, 1. January 1928,
00:00:00 clocks were turned backward 0:05:52 hours to Saturday, 31.
December 1927, 23:54:08 local standard time instead



This is not particularly strange and has happened pretty much everywhere at one time or another as timezones were switched or changed due to political or administrative actions.





@Jason: For the bedtime reading, I'd suggest the (now) IANA timezone database (previously administered by a lovely guy named Olson, I think) would be a great resource: iana.org/time-zones. As far as I know, a majority of the open source world (thus mentioned libraries) use this as their primary source of timezone data.
– Sune Rasmussen
Mar 11 '12 at 21:25



The moral of this strangeness is:





Conversion/storage into UTC really wouldn't help for the problem described as you would encounter the discontinuity in the conversion to UTC.
– unpythonic
Jul 30 '11 at 4:28





@Mark Mann: if your program uses UTC internally everywhere, converting to/from a local time-zone only in the UI, you would not care about such discontinuities.
– Raedwald
Aug 26 '11 at 11:50





@Raedwald: Sure you would - What is the UTC time for 1927-12-31 23:54:08? (Ignoring, for the moment, that UTC didn't even exist in 1927). At some point this time and date are coming into your system, and you have to decide what to do with it. Telling the user they have to input time in UTC just moves the problem to the user, it doesn't eliminate it.
– Nick Bastin
Feb 19 '12 at 22:39





I feel vindicated at the amount of activity on this thread, having been working on date/time refactoring of a large app for almost a year now. If you're doing something like calendaring, you can't "simply" store UTC, as the definitions of time zones in which it may be rendered will change over time. We store "user intent time" - the user's local time and their time zone - and UTC for searching and sorting, and whenever the IANA database is updated, we recalculate all the UTC times.
– taiganaut
Dec 7 '12 at 22:34



When incrementing time you should convert back to UTC and then add or subtract. Use the local time only for display.



This way you will be able to walk through any periods where hours or minutes happen twice.



If you converted to UTC, add each second, and convert to local time for display. You would go through 11:54:08 p.m. LMT - 11:59:59 p.m. LMT and then 11:54:08 p.m. CST - 11:59:59 p.m. CST.



Instead of converting each date, you use the following code


long difference = (sDt4.getTime() - sDt3.getTime()) / 1000;
System.out.println(difference);



And see the result is:


1





I'm afraid that's not the case. You can try my code in you system, it will output 1, because we have different locales.
– Freewind
May 16 '12 at 5:39


1





That's only true because you have not specified the locale in the parser input. That's bad coding style and a huge design flaw in Java -- its inherent localization. Personally, I put "TZ=UTC LC_ALL=C" everywhere I use Java to avoid that. In addition you should avoid every localized version of an implementation unless you are directly interacting with a user and explicitly want it. Don't to ANY calculations including localizations, always use Locale.ROOT and UTC timezones unless absolutely necessary.
– user1050755
Nov 26 '14 at 15:53



I'm sorry to say that, but the time discontinuity has moved a bit in



JDK 6 two years ago, and in JDK 7 just recently in update 25.



Lesson to learn: avoid non-UTC times at all costs, except, maybe, for display.





This is incorrect. The discontinuity isn't a bug - it's just that a more recent version of TZDB has slightly different data. For example, on my machine with Java 8, if you change the code very slightly to use "1927-12-31 23:54:02" and "1927-12-31 23:54:03" you'll still see a discontinuity - but of 358 seconds now, instead of 353. Even more recent versions of TZDB have yet another difference - see my answer for details. There's no real bug here, just a design decision around how ambiguous date/time text values are parsed.
– Jon Skeet
Oct 30 '14 at 17:50






The real problem is that programmers don't understand that conversion between local and universal time (in either direction) is not and cannot be 100% reliable. For old timestamps the data we have on what local time was is shaky at best. For future timestamps political actions can change what universal time a given local time maps to. For current and recent past timestamps you can have the problem that the process of updating the tz database and rolling out the changes can be slower than than the implementation schedule of the laws.
– plugwash
Mar 14 '17 at 16:06



As explained by others, there's a time discontinuity there. There are two possible timezone offsets for 1927-12-31 23:54:08 at Asia/Shanghai, but only one offset for 1927-12-31 23:54:07. So, depending on which offset is used, there's either a one second difference or a 5 minutes and 53 seconds difference.


1927-12-31 23:54:08


Asia/Shanghai


1927-12-31 23:54:07



This slight shift of offsets, instead of the usual one-hour daylight savings (summer time) we are used to, obscures the problem a bit.



Note that the 2013a update of the timezone database moved this discontinuity a few seconds earlier, but the effect would still be observable.



The new java.time package on Java 8 let use see this more clearly, and provide tools to handle it. Given:


java.time


DateTimeFormatterBuilder dtfb = new DateTimeFormatterBuilder();
dtfb.append(DateTimeFormatter.ISO_LOCAL_DATE);
dtfb.appendLiteral(' ');
dtfb.append(DateTimeFormatter.ISO_LOCAL_TIME);
DateTimeFormatter dtf = dtfb.toFormatter();
ZoneId shanghai = ZoneId.of("Asia/Shanghai");

String str3 = "1927-12-31 23:54:07";
String str4 = "1927-12-31 23:54:08";

ZonedDateTime zdt3 = LocalDateTime.parse(str3, dtf).atZone(shanghai);
ZonedDateTime zdt4 = LocalDateTime.parse(str4, dtf).atZone(shanghai);

Duration durationAtEarlierOffset = Duration.between(zdt3.withEarlierOffsetAtOverlap(), zdt4.withEarlierOffsetAtOverlap());

Duration durationAtLaterOffset = Duration.between(zdt3.withLaterOffsetAtOverlap(), zdt4.withLaterOffsetAtOverlap());



Then durationAtEarlierOffset will be one second, while durationAtLaterOffset will be five minutes and 53 seconds.


durationAtEarlierOffset


durationAtLaterOffset



Also, these two offsets are the same:


// Both have offsets +08:05:52
ZoneOffset zo3Earlier = zdt3.withEarlierOffsetAtOverlap().getOffset();
ZoneOffset zo3Later = zdt3.withLaterOffsetAtOverlap().getOffset();



But these two are different:


// +08:05:52
ZoneOffset zo4Earlier = zdt4.withEarlierOffsetAtOverlap().getOffset();

// +08:00
ZoneOffset zo4Later = zdt4.withLaterOffsetAtOverlap().getOffset();



You can see the same problem comparing 1927-12-31 23:59:59 with 1928-01-01 00:00:00, though, in this case, it is the earlier offset that produce the longer divergence, and it is the earlier date that has two possible offsets.


1927-12-31 23:59:59


1928-01-01 00:00:00



Another way to approach this is to check whether there's a transition going on. We can do this like this:


// Null
ZoneOffsetTransition zot3 = shanghai.getRules().getTransition(ld3.toLocalDateTime);

// An overlap transition
ZoneOffsetTransition zot4 = shanghai.getRules().getTransition(ld3.toLocalDateTime);



You can check whether the transition is an overlap - in which case there's more than one valid offset for that date/time - or a gap - in which case that date/time is not valid for that zone id - by using the isOverlap() and isGap() methods on zot4.


isOverlap()


isGap()


zot4



I hope this helps people handle this sort of issue once Java 8 becomes widely available, or to those using Java 7 who adopt the JSR 310 backport.





Hi Daniel, I have run your piece of code but it is not giving output as expected. like durationAtEarlierOffset and durationAtLaterOffset both are 1 second only and also zot3 and zot4 both are null. I have set just copied and run this code on my machine. is there anything which needs to be done here. Let me know if you want to see a piece of code. Here is code tutorialspoint.com/… can you let me know what going on here.
– vineeshchauhan
Jun 15 '17 at 10:30





@vineeshchauhan It depends on Java's version, because this has changed in tzdata, and different versions of JDK bundle different versions of tzdata. On my own installed Java, the times are 1900-12-31 23:54:16 and 1900-12-31 23:54:17, but that doesn't work on the site you shared, so they are using a different Java version than I.
– Daniel C. Sobral
Jul 21 '17 at 0:38


1900-12-31 23:54:16


1900-12-31 23:54:17



IMHO the pervasive, implicit localization in Java is its single largest design flaw. It may be intended for user interfaces, but frankly, who really uses Java for user interfaces today except for some IDEs where you can basically ignore localization because programmers aren't exactly the target audience for it. You can fix it (especially on linux servers) by:



To the Java Community Process members I recommend:



I mean, come on, aren't global static variables an anti-OO pattern? Nothing else are those pervasive defaults given by some rudimentary environment variables.......




Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).


Would you like to answer one of these unanswered questions instead?

Zj sHOoI6,aZwSjsmAlmqTcsj3
8FVbR3ZdhMv8,xQ,ds624nPsTywKtBLOGg wdPu3UrvZD ntR0zyEg VAW3BOMeTXDZFwfh,Or,VEN,L EKVK9Xu7 3Ia,PmKvuEgpos,Y4m

Popular posts from this blog

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?

Create weekly swift ios local notifications