标签云

微信群

扫码加入我们

WeChat QR Code

为什么是减去这两次(1927)给一个奇怪的结果呢?

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?

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.


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 ?

2018年05月23日37分00秒

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?"

2018年05月23日37分00秒

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.

2018年05月23日37分00秒

originally posted as Oracle Bug ID 7070044 on Jul 23 `11

2018年05月23日37分00秒

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".

2018年05月23日37分00秒

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...

2018年05月23日37分00秒

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

2018年05月23日37分00秒

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.

2018年05月23日37分00秒

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.

2018年05月23日37分00秒

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.

2018年05月23日37分00秒

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.

2018年05月23日37分00秒

Conversion/storage into UTC really wouldn't help for the problem described as you would encounter the discontinuity in the conversion to UTC.

2018年05月23日37分00秒

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.

2018年05月23日37分00秒

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.

2018年05月23日37分00秒

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.

2018年05月23日37分00秒

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.

1970年01月01日00分03秒

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.

2018年05月23日37分00秒

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.

2018年05月23日37分00秒

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.

2018年05月23日37分00秒

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.

2018年05月23日37分00秒

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.

2018年05月23日37分00秒