Java – use jodatime to UTC to local time in milliseconds

I try to use jodatime to display transactions in a specific time period

Our server requires the start date and end date to be UTC (this may be obvious) Therefore, any business logic around them uses the datetime object, and the time zone is set to datetimezone UTC, for example,

mStartDate = DateTime.Now(UTC).withTimeAtStartOfDay();

This is effective except to show that I don't know how to increase its time for the local (system default) time zone Ideally, I want to use the dateutils formatdaterange function that passes two local timestamps However, the getmillis() function does not seem to consider the local offset:

I've tried this too:

mTimePeriodTitle.setText(DateUtils.formatDateRange(mContext,f,mStartDate.getMillis(),mEndDate.getMillis(),DateUtils.FORMAT_SHOW_TIME,TimeZone.getDefault().getID()).toString());

But it makes no difference So my question is how to get a well formed local date range with 2 UTC timestamps?

Solution

If your datetime is UTC and you want to convert it to another time zone, you can use the withzone method for conversion

For the following example, my default time zone is America / Sao_ Paulo (you can use datetimezone. Getdefault() to check your time zone):

// create today's date in UTC
DateTime mStartDate = DateTime.Now(DateTimeZone.UTC).withTimeAtStartOfDay();
// date/time in UTC
System.out.println(mStartDate); // 2017-06-13T00:00:00.000Z
// date/time in my default timezone (America/Sao_Paulo)
System.out.println(mStartDate.withZone(DateTimeZone.getDefault())); // 2017-06-12T21:00:00.000-03:00

The output is:

Please note that the withzone method correctly converts the date and time into my time zone (in America / sao_paulo, the current offset is utc-03:00), so it has been adjusted accordingly

If you want to get the time (hours / minutes / seconds), you can use the tolocaltime() method:

System.out.println(mStartDate.withZone(DateTimeZone.getDefault()).toLocalTime()); // 21:00:00.000

The output is:

If you want a different format (for example, not printing the 3-digit number of seconds), you can use datetimeformatter The advantage is that you can set the time zone in the formatter, so you don't need to convert datetime:

// create formatter for hour/minute/second,set it with my default timezone
DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm:ss").withZone(DateTimeZone.getDefault());
System.out.println(fmt.print(mStartDate)); // 21:00:00

The output is:

To get the scope, you can use one of the above methods and datetime (mstartdate and menddate), and use datetimeformatter to change it to any format you need

PS: I think what you lack when using getmillis() is that the date and time (UTC and default time zone) represent the same time You just convert this moment into local time, but the milliseconds are the same (think, at this moment, everyone in the world is at the same time (the same milliseconds), but their local time may be different, depending on where they are) Therefore, when converting UTC datetime to another time zone, we only find the local time in the region, which corresponds to the same millis

You can use the getmillis () method to check on two objects:

System.out.println(mStartDate.getMillis()); // 1497312000000
System.out.println(mStartDate.withZone(DateTimeZone.getDefault()).getMillis()); // 1497312000000

Note that even if I convert the object to another time zone, the millis remains the same (149731200000) That's because both represent the same time. I just move them to another time zone, where their local time is different

Java's new date / time API

Joda - time is disabled and replaced by a new API, so I don't recommend starting a new project with it If this is the case, you can consider using the new date / time API, but if you use joda's code base is large or you don't want to migrate it now, you can consider the rest of the answers

In any case, even in joda's website, it says: "please note that joda time is considered to be a largely completed project. There is no plan to make major improvements. If you use Java se 8, please migrate to Java. Time (jsr-310). *."

If you are using java 8, consider using new Java time API. Less bugged and less error prone than the old APIs I'm not sure if it's already available for all Android versions (but see alternatives below)

If you use Java < = 7, you can use threeten backup, which is a good back end for the new date / time class of Java 8 For Android, there is a way to use it, using threetenabp (more about how to use it here)

The following codes apply to both The only difference is the package name (Java. Time in Java 8 and org. Time in threeten backup (or threetenabp for Android) threeten. BP), but the class and method names are the same

To get the current date starting with UTC, you can do the following:

// UTC's today at start of the day
zoneddatetime utc = LocalDate.Now(ZoneOffset.UTC).atStartOfDay(ZoneOffset.UTC);
System.out.println(utc); // 2017-06-13T00:00Z

First, I use localdate Now (zoneoffset. UTC) to find the current local date in UTC If I only use localdate Now (), which will get the current date in my default time zone, which is not what we want (it may be different from UTC, depending on where – when – what you are and what the default time zone is)

Then I use atstartofday (zoneoffset. UTC) to get the start of the UTC day I know that using UTC twice sounds redundant, but the API allows us to use any time zone in this method, and IMO specifies the time zone we want (if the date is a time zone that changes in daylight saving time, the beginning of the day may not be midnight - the time zone parameter is to ensure that the correct value is set)

The output is:

To convert to my default time zone, I can use zoneid Systemdefault(), in my example, returns America / Sao_ Paulo. To convert it and get only the local time part, just do the following:

System.out.println(utc.withZoneSameInstant(ZoneId.systemDefault()).toLocalTime()); // 21:00

The output is:

If you want to change it, you can also use the formatter:

// formatter for localtime (hour/minute/second)
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("HH:mm:ss");
System.out.println(fmt.format(utc.withZoneSameInstant(ZoneId.systemDefault()))); // 21:00:00

The output is:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>