走过、路过、错过

SimpleDateFormat TimeZone Date转String,String转Date

国际化项目中经常遇到将时区A时间time转为B时区时间time2,简单的的可以直接计算毫秒数的差值进行处理。

有时目标时区不确定,服务有可能运行在不同时区,有时还有比较复杂的时间计算,通过计算毫秒值得方式就很繁琐。

通过设置SimpleDateFormat 的TimeZone ,使用format、parse可简化操作

 

-- 输出GMT+0时间string,now为本机系统时区的时间,targetString输出为GMT+0时间

Date now = new Date();

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

format.setTImeZone(TimeZone.getTimeZone("GMT+0"));

String targetString = format.format(now);

 

-- 输出为系统时区的Date,dateString 被认为是GMT+0时间,targetDate 为系统时区的时间

String dateString = "2020-09-08 23:14:00 ";

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

format.setTImeZone(TimeZone.getTimeZone("GMT+0"));

Date targetDate = format.parse(now);

posted @ 2020-09-08 23:18  行者武松  阅读(439)  评论(0编辑  收藏  举报