Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert UTC time to some other time zone ("CST","IST")

In my Android application server will return some UTC date in following format(yyyy-MM-dd HH:mm:ss) 24hours and I need to convert those time into user's TimeZone for example CST, IST.

I did the following code but I do know is it correct or not, please assist me to do the time zone conversion in right way.

I get UTC date as json string and converting into user's time zone format and showing Android side

private static Date utcDate;
private static DateFormat expireFormat = new SimpleDateFormat(
        "yyyy-MM-dd HH:mm:ss");

        try {
            expireFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            utcDate = expireFormat.parse("2014-04-01 10:32:00");
            System.out.println(TimeZone.getDefault().getID());
            expireFormat.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getID()));
            System.out.println(expireFormat.format(utcDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }

    output of the code:
    Asia/Calcutta
    2014-04-01 16:02:00
like image 224
M.A.Murali Avatar asked Oct 01 '22 04:10

M.A.Murali


1 Answers

The overall approach is OK if a re-formatted String is really what you're trying to get.

There are some issues though

  1. SimpleDateFormat is not a threadsafe class. Setting it to a static field inside a server is a problem!

  2. Same as #1 regarding using a static field to hold the intermediate Date object.

  3. Is "CST" China Standard Time? Central Standard Time (US or Australia)? Cuba Standard Time? Three letter abbreviations TimeZone are bad news in general. Try to use an Olson Name or Alias if at all possible.

  4. Is this the server side or the android? If it's a server, you could probably benefit from the new Java 8 API for DateTime handling.

like image 178
Affe Avatar answered Oct 20 '22 23:10

Affe