TimeZone with Calendar confusing results

前端 未结 5 2067
情深已故
情深已故 2021-01-06 06:19

I have been working with timezone conversions lately and am quite astonished by the result i get.Basically, i want to convert a date from one timezone into another. below is

5条回答
  •  花落未央
    2021-01-06 06:43

    Are you restricted to using TimeZone and Calendar? If not I suggest using the excellent Library JodaTime which makes handling time zones much easier.

    Your example would then look like this:

    public static void convertTimeZoneJoda(String date, String time, DateTimeZone fromTimezone, DateTimeZone toTimeZone) {
        DateTimeFormatter dtf = DateTimeFormat.forPattern("dd/MM/yyyyHH:mm").withZone(fromTimezone);
        DateTime dt = dtf.parseDateTime(date+time).withZone(toTimeZone);
    
        System.out.println("Time in " + toTimeZone.getID() + " : " + dt.toString());
    }
    
    public static void main(String[] args) {
        convertTimeZoneJoda("23/04/2013", "23:00", DateTimeZone.forID("EST5EDT"), DateTimeZone.forID("GMT"));
    }
    

    JodaTime also allows for convenient conversation between TimeZone and DateTimeZone.

提交回复
热议问题