0

I want to get the local time in millseconds from UTC milliseconds... I tried following code.. But it return same UTC time instead of local time.

private long getLocalTimeFromUTC(long aLong) {
    TimeZone timeZone = TimeZone.getTimeZone("UTC");
    Calendar calendar = Calendar.getInstance(timeZone);
    calendar.setTimeInMillis(aLong);
    Calendar calendar1 = Calendar.getInstance(TimeZone.getDefault());
    calendar1.setTimeInMillis(calendar.getTimeInMillis());
    return calendar1.getTimeInMillis();
}

Actually I don't want DateFormat String, I need milliseconds back... That's why I used Calendar instance.

Gunaseelan
  • 14,415
  • 11
  • 80
  • 128

1 Answers1

0

The code you wrote creates two Calendars with the same timestamp in two different time zones, so of course the value of getTimeInMillis will be the same. There are three components to a date - the time zone, the milliseconds since epoch, and the date fields - and when you set two of these, the third is derived from them. So what you should be setting in addition to the time zone, is the date fields, so that the milliseconds value can be derived.

private long getLocalTimeFromUTC(long aLong) {
    TimeZone timeZone = TimeZone.getTimeZone("UTC");
    Calendar calendar = Calendar.getInstance(timeZone);
    calendar.setTimeInMillis(System.currentTimeMillis());

    Calendar calendar1 = Calendar.getInstance(TimeZone.getDefault());
    // 7 date fields: YEAR, MONTH, DAY_OF_MONTH, 
    // HOUR_OF_DAY, MINUTE, SECOND, and MILLISECOND
    // they come from "import static java.util.Calendar.*;"
    calendar1.set(calendar.get(YEAR), 
                  calendar.get(MONTH),
                  calendar.get(DAY_OF_MONTH),
                  calendar.get(HOUR_OF_DAY),
                  calendar.get(MINUTE),
                  calendar.get(SECOND));
    calendar1.set(MILLISECOND, calendar.get(MILLISECOND));
    return calendar1.getTimeInMillis();
}
Leo Aso
  • 11,898
  • 3
  • 25
  • 46
  • `1553509009000` is my UTC time, When I convert it back using your answer I'm getting `1553489209000`. Which is one hour extra. – Gunaseelan Mar 25 '19 at 10:21
  • `1553489209000 - 1553509009000` is not 1 hour extra, it's 5 and a half hours extra, which is correct if you live in India. Recheck your calculation. – Leo Aso Mar 25 '19 at 12:00