使用Java中的timezoneoffset将本地时间转换为UTC
我有一个本地日期/时间戳,我有一个以字符串格式存储的时区偏移量(myStringTimeStamp下面的变量名)。我需要将本地日期/时间戳转换为UTC时间 时间戳的格式为:yyyy-MM-dd HH:MM:ss 我尝试了以下方面的变化:使用Java中的timezoneoffset将本地时间转换为UTC,java,date,datetime,Java,Date,Datetime,我有一个本地日期/时间戳,我有一个以字符串格式存储的时区偏移量(myStringTimeStamp下面的变量名)。我需要将本地日期/时间戳转换为UTC时间 时间戳的格式为:yyyy-MM-dd HH:MM:ss 我尝试了以下方面的变化: SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
//Convert timestamp to date
Date d = sdf.parse(myStringTimeStamp, new ParsePosition(0));
newTimeStamp = sdf.format(d);
但我似乎找不出正确的公式。有什么帮助吗
我无法使用第三方库/框架。问题似乎是因为您在解析之前设置了目标时区 首先解析,然后设置时区,最后格式化
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
//Convert timestamp to date
Date d = sdf.parse(myStringTimeStamp, new ParsePosition(0));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
newTimeStamp = sdf.format(d);
您是否尝试过:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
//Convert timestamp to date
Date d = sdf.parse(myStringTimeStamp, new ParsePosition(0));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
newTimeStamp = sdf.format(d);
如果可能的话,使用
java.time
包(在Java8中)或Joda时间库(在Java7中)!谢谢你的帮助!