Get date in current timezone in java

前端 未结 4 842
遇见更好的自我
遇见更好的自我 2020-12-05 00:03

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 m

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 00:49

    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);
    

提交回复
热议问题