如何将日期/时间从一个时区转换为另一个时区? [英] How do I convert date/time from one timezone to another?

查看:199
本文介绍了如何将日期/时间从一个时区转换为另一个时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将日期/时间从 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
}

这篇关于如何将日期/时间从一个时区转换为另一个时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆