Home » Android » java – Display UTC date/time into date/time according to the current time-zone

java – Display UTC date/time into date/time according to the current time-zone

Posted by: admin June 15, 2020 Leave a comment

Questions:

I am getting a date/time string from web in the format of “yyyy/mm/dd’T’HH:MM:SS’Z'” and it is in UTC.

Now i have to identify the current time zone of device and then convert this time to my local time..

How do i do it, pls suggest me !!

(FYI, Currently, UTC time is 10:25 AM, in india current time is 3:55 PM)

How to&Answers:

Try using TimeZone.getDefault() instead of TimeZone.getTimeZone("GMT")

From the docs:

… you get a TimeZone using
getDefault which creates a TimeZone
based on the time zone where the
program is running.

EDIT: You can parse date using SimpleDateFormat (there is also the documentation on the format string there). In your case, you want to do (untested):

 // note that I modified the format string slightly
 SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd'T'HH:mm:ss'Z'");
 // set the timezone to the original date string's timezone
 fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
 Date date = fmt.parse("1998/12/21T13:29:31Z", new ParsePosition(0));

 // then reset to the target date string's (local) timezone
 fmt.setTimeZone(TimeZone.getDefault());
 String localTime = fmt.format(date);

alternatively, use two separate instances of SimpleDateFormat, one for original and one for target time.