如何将日期/时间从一个时区转换为另一个时区?

问题描述:

是否可以将日期/时间从 EST (America / New_York)转换为 UTC ,给定格式为的字符串yyyy-MM-dd HH:mm:ss

Is it possible to convert date/time from EST (America/New_York) into UTC, given string in format yyyy-MM-dd HH:mm:ss?

示例:

getUTCfromNY("2015-11-01 01:00:00", "NY");

应输出:

GMT Time: 2015-11-01 06:00:00

编辑

在以下两个结果之间,您应该选择哪一个?

Between the two results below, which one should you take?

getUTCfromNY(2015-11-01 01:00:00,NY) GMT时间:2015-11-01 06 :00:00

getUTCfromNY("2015-11-01 01:00:00", "NY") GMT Time: 2015-11-01 06:00:00

getUTCfromNY(2015-11-01 01:00:00,NY) GMT时间: 2015-11-01 05 :00:00

getUTCfromNY("2015-11-01 01:00:00", "NY") GMT Time: 2015-11-01 05:00:00

SimpleDateFormat# setTimezone()就是答案。一个带有 ETC 时区的格式化程序,用于解析,另一个用 UTC 生成输出字符串:

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
}