简体   繁体   中英

Python vs Java UTC?

I've been having some problems with a time-based application I'm developing, which uses Java in the Android client side and Python in the server side. I encountered a discrepancy of -3 hours (which is exactly the timezone from the Android device) in the times reported by Java and Python, even though in both sides I'm getting the time in a way that (according to SO and other sites) returns a UTC time. In my client, I'm using

Date utcNow = new Date()

and in the server, i use

datetime.datetime.now()

Yet, when run at the same time, they yield 2013-09-09 11:52:16 and 2013-09-09 14:52:16 , respectively. I suspect the issue is on Java side, since running date in the server returns the same value as Python (obviously), with the timezone UTC, and the same command in the Android device returns a BRT (GMT-3) time.

While searching for timezone adjustment on both languages, all answers claimed that the methods above would return a UTC date, yet this difference is clearly visible.

How can I convert the Android device's time to UTC?

Right now I'm using a really ugly (and extremely deprecated) solution: utcNow.setHours(utcNoe.getHours()+3)

EDIT: Side note: From Jon's answer, I noticed Java's Date objects are equivalent to Python's naive datetime objects.

I strongly suspect the problem is in the code you haven't shown us - when you convert the Date to a String in Java via SimpleDateFormat .

A Date itself is just an instant in time, with no time zone or calendar system associated with it. In order to convert it to a string, both need to be applied - and the default time zone in a SimpleDateFormat is the system local time zone.

If you just change your code to:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                                               Locale.US);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateText = format.format(date);

then I suspect your problems will go away. Note that this is not part of the Date information itself. (It's really important to understand that.)

Also note that the date/time API in Java is pretty horrible. If you're able to use Joda-Time instead, you're likely to have a better time of it. (It would be overkill if all you need is a timestamp, but if you have any actual date/time work to do, you should definitely consider it.)

This has been asked many times before. Have a look at Set Time Zone . You can also use this approach to change the timezone.

--- EDIT If you want to transmit your timezone as a string, you should transmit it using ISO_8601 that way you can adjust the time on your server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM