Convert UTC into Local Time on Android

JavaAndroidUtc

Java Problem Overview


In my project, I have get the API response in json format. I get a string value of time in UTC time format like this Jul 16, 2013 12:08:59 AM.
I need to change this into Local time. That is where ever we use this the app needs to show the local time. How to I do this?

Here is some Code I have tried:

String aDate = getValue("dateTime", aEventJson);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss z");
simpleDateFormat.setTimeZone(TimeZone.getDefault());
String formattedDate = simpleDateFormat.format(aDate);

Assume aDate contains Jul 16, 2013 12:08:59 AM

Java Solutions


Solution 1 - Java

Here's my attempt:

String dateStr = "Jul 16, 2013 12:08:59 AM";
SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss a", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = df.parse(dateStr);
df.setTimeZone(TimeZone.getDefault());
String formattedDate = df.format(date);

Also notice the "a" for the am/pm marker...

Solution 2 - Java

I should like to contribute the modern answer. While SimpleDateFormat was the class we had for parsing and formatting date-times in 2013 (apart from Joda-Time), it is now long outdated, and we have so much better in java.time or JSR-310, the modern Java date and time API that came out with Java 8 in 2014.

But most Android devices still don’t run Java 8, I hear you say. Fortunately you can still use the modern Java date and time API on them through the ThreeTenABP, the backport of JSR-310 to Android Java 7. Details are in this question: How to use ThreeTenABP in Android Project.

Now the code is:

	DateTimeFormatter formatter 
			= DateTimeFormatter.ofPattern("MMM dd, uuuu hh:mm:ss a", Locale.ENGLISH);
	String aDate = "Jul 16, 2013 12:08:59 AM";
	String formattedDate = LocalDateTime.parse(aDate, formatter)
			.atOffset(ZoneOffset.UTC)
			.atZoneSameInstant(ZoneId.systemDefault())
			.format(formatter);
	System.out.println(formattedDate);

Since my computer is running Europe/Copenhagen time zone, which in July is 2 hours ahead of UTC, this prints

Jul 16, 2013 02:08:59 AM

Further points:

  • Since you have AM in your string, I assumed your hours are within AM, from 1 through 12. To parse and format them correctly you need lowercase h in the format pattern string. Uppercase H is for hour-of-day from 0 through 23.
  • Prefer to give an explcit locale to the formatter (whether SimpleDateFormat or DateTimeFormatter). If no locale is given, the formatter will use the device’s default locale. “Jul” and “AM” are in English, and your code may run nicely on many devices until one day it runs on a device with non-English locale and crashes, and you have a hard time figuring out why.
  • If you can, give the desired time zone explictly, for example as ZoneId.of("Asia/Kolkata"). The JVM’s default time zone may be changed by other parts of your program or other programs running in the same JVM, so is not reliable.

Solution 3 - Java

1.Local to UTC Converter

public static String localToUTC(String dateFormat, String datesToConvert) {


        String dateToReturn = datesToConvert;

        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        sdf.setTimeZone(TimeZone.getDefault());
        Date gmt = null;

        SimpleDateFormat sdfOutPutToSend = new SimpleDateFormat(dateFormat);
        sdfOutPutToSend.setTimeZone(TimeZone.getTimeZone("UTC"));

        try {

            gmt = sdf.parse(datesToConvert);
            dateToReturn = sdfOutPutToSend.format(gmt);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateToReturn;
    }

2. UTC to Local Converter

public static String uTCToLocal(String dateFormatInPut, String dateFomratOutPut, String datesToConvert) {


    String dateToReturn = datesToConvert;

    SimpleDateFormat sdf = new SimpleDateFormat(dateFormatInPut);
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    Date gmt = null;

    SimpleDateFormat sdfOutPutToSend = new SimpleDateFormat(dateFomratOutPut);
    sdfOutPutToSend.setTimeZone(TimeZone.getDefault());

    try {

        gmt = sdf.parse(datesToConvert);
        dateToReturn = sdfOutPutToSend.format(gmt);

    } catch (ParseException e) {
        e.printStackTrace();
    }
    return dateToReturn; }

Solution 4 - Java

//your UTC time var
long time = UTCtime;

//convert it
Time timeFormat = new Time();
timeFormat.set(time+TimeZone.getDefault().getOffset(time));

//use the value
long localTime = timeFormat.toMillis(true);

Solution 5 - Java

Use the following code.

TimeZone defaultTimeZone = TimeZone.getDefault();
String strDefaultTimeZone = defaultTimeZone.getDisplayName(false, TimeZone.SHORT);

//The code you use
String aDate = getValue("dateTime", aEventJson);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss z");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(strDefaultTimeZone));
String formattedDate = simpleDateFormat.format(aDate);

This should work.

Solution 6 - Java

This is how i do it on android Build.VERSION.SDK_INT < 26

int offset = TimeZone.getDefault().getRawOffset();
String str_date='20:30 12-01-2021';
DateFormat formatter = new SimpleDateFormat("HH:mm dd-MM-yyy",Locale.US);
Date date = formatter.parse(str_date);
long utcTime = date.getTime() + (3600000*3);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm dd/MM/yyyy", Locale.US);
String dateStr = sdf.format(utcTime + offset);
System.out.println(dateStr);

As my server sends the time with -3 timezone i have to add (3600*3) to getTime and i save it into utcTime, this way utcTime is in UTC. And then i add to utcTime the offset of the phone current timezone. In my case as my timezone is -3 its prints:

20:30 12/01/2021

But if i change my time zone the date also changes.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMadTechView Question on Stackoverflow
Solution 1 - JavadevconsoleView Answer on Stackoverflow
Solution 2 - JavaOle V.V.View Answer on Stackoverflow
Solution 3 - JavaRonak GadhiaView Answer on Stackoverflow
Solution 4 - JavaTom BevelanderView Answer on Stackoverflow
Solution 5 - JavaSalman KhakwaniView Answer on Stackoverflow
Solution 6 - Javauser3486626View Answer on Stackoverflow