Date and time conversion to some other Timezone in java

后端 未结 10 487
失恋的感觉
失恋的感觉 2020-12-11 21:13

i have written this code to convert the current system date and time to some other timezone. I am not getting any error but i am not getting my output as expected. Like if i

10条回答
  •  一个人的身影
    2020-12-11 21:46

    SimpleDateFormat#setTimezone() is the answer. One formatter with ETC timezone you use for parsing, another with UTC for producing output string:

    DateFormat dfNy = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT);
    dfNy.setTimeZone(TimeZone.getTimeZone("EST"));
    DateFormat dfUtc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT);
    dfUtc.setTimeZone(TimeZone.getTimeZone("UTC"));
    
    try {
        return dfUtc.format(dfNy.parse(input));
    } catch (ParseException e) {
        return null;              // invalid input
    }
    

提交回复
热议问题