TimeZone with Calendar confusing results

前端 未结 5 2093
情深已故
情深已故 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:59

    The internal representation of the given date is not evaluated until really needed, that is until you try to access it by those getters. However the best way of parsing dates is through SimpleDateFormat.


    EDIT (added for summarize the comments below and to better clarify my answer).

    Calendar works this way for better efficiency: instead of recalculate everithing each time you call a setter, it waits until you call a getter.

    Calendar should be used mainly for date calculations (see add() and roll()), but you are using it for parsing and formatting: these tasks are better accomplished with SimpleDateFormat, that's why I say that your usage of Calendar is not elegant.

    See this example:

    private static void convertTimeZone(String date, String time,
                TimeZone fromTimezone, TimeZone toTimeZone) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        df.setTimeZone(fromTimezone);
        Date d = df.parse(date + " " + time);
        df.setTimeZone(toTimeZone);
        System.out.println("Time in " + toTimeZone.getDisplayName() + " : " +
                           df.format(d));
    }
    

    I have reimplemented your method using SimpleDateFormat only. My method is smaller, there is no splitting logic (it's hidden in parse()), and also the output is handled in a simpler way. Furthermore the date format is expressed in a compact and standard way that can be easily internationalized using a ResourceBundle.

    Also note that the timezone conversion is just a formatting task: the internal representation of the parsed date does not change.

提交回复
热议问题