javadatedatetimecalendartimezone

Get date in current timezone in Java


I have been searching over the net from past few hours to get the datetime in my system timezone.

When I use calendar.getTimezone.getDefaultName()it always returns me GMT. Ideally it should return my current timezone, which is IST.

I am trying to convert this string "2014-02-14T06:04:00:00", which is in GMT to my timezone datetime. It always returns me the same time in GMT.

All I see is that everyone is suggesting to use Timezone, i.e,

dateFormatter.setTimezone("any_arbitary_timezone");

Point is my application will be used in different geographical locations. I cannot set it to a particular timezone. It should be set to the system timezone, so that it can display in whichever timezone the user is currently in.


Solution

  • Here is a way to get the id of a TimeZone that matches your local system clock's offset,

    Calendar cal = Calendar.getInstance();
    long milliDiff = cal.get(Calendar.ZONE_OFFSET);
    // Got local offset, now loop through available timezone id(s).
    String [] ids = TimeZone.getAvailableIDs();
    String name = null;
    for (String id : ids) {
      TimeZone tz = TimeZone.getTimeZone(id);
      if (tz.getRawOffset() == milliDiff) {
        // Found a match.
        name = id;
        break;
      }
    }
    System.out.println(name);