Convert UTC time to LOCAL time

Date and time manipulations are one of the hardest things to do right when programming for a global user base.

When users of a system, e.g. a mobile application, have different time zones, it can be challenging to manage dates and time in the local system in manner that looks consistent to all users.  Here is quick solution for this challenging  task.

Here is quick solution for converting UTC time to local time in android or java:

private static String convertInLocalTime(String DATE_FORMAT, String serverDate) {
    // String DATE_FORMAT = "yyyy-MM-dd HH:mm";
    String strDate = "";
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
    try {
        TimeZone utcZone = TimeZone.getTimeZone("UTC");
        sdf.setTimeZone(utcZone);// Set UTC time z one
        Date myDate = sdf.parse(serverDate);
        sdf.setTimeZone(TimeZone.getDefault());// Set device time zone
        strDate = sdf.format(myDate);
        // Log.d("date=", "UTC to Local2 >> " + strDate);
        return strDate;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return strDate;
}

And you can call this function like below:

String convertedDate= convertInLocalTime(“yyyy-MM-dd hh:mm”, “2018-01-02 10:10”);

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.