Java如何将GMT格式datetime字符串转换为本地时间
Java GMT时间字符串转本地时间实现方案
推荐实现(Java 8 及以上版本)
优先使用java.time包下的类实现,避免旧日期API线程不安全、设计不合理的问题,示例代码如下:
import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; public class GmtToLocalTime { public static void main(String[] args) { // 输入的GMT时间字符串 String gmtTimeStr = "2021-05-26 14:23"; // 构造格式化器,指定时间格式和原始时区为GMT DateTimeFormatter gmtFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm") .withZone(ZoneId.of("GMT")); // 解析字符串为GMT时区的时间,再转换为本地系统默认时区的时间 ZonedDateTime localTime = ZonedDateTime.parse(gmtTimeStr, gmtFormatter) .withZoneSameInstant(ZoneId.systemDefault()); // 自定义输出格式,按需调整pattern即可 DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); System.out.println("转换后的本地时间:" + outputFormatter.format(localTime)); } }
- 如果你所在时区为东8区(北京时间),上述代码输出结果为:
转换后的本地时间:2021-05-26 22:23 withZoneSameInstant方法保证转换前后对应同一个时间点,仅变更时区展示- 可根据业务需求自定义输入、输出的时间格式,调整
ofPattern的参数即可
兼容旧版本实现(Java 7及更早,不推荐)
如果必须兼容低版本Java,可使用SimpleDateFormat实现,注意该类不是线程安全的,不要在多线程环境下共享实例:
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; public class GmtToLocalTimeOld { public static void main(String[] args) throws ParseException { String gmtTimeStr = "2021-05-26 14:23"; SimpleDateFormat gmtSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); // 指定原始时间时区为GMT gmtSdf.setTimeZone(TimeZone.getTimeZone("GMT")); Date date = gmtSdf.parse(gmtTimeStr); // 输出本地时间,SimpleDateFormat默认使用系统本地时区 SimpleDateFormat localSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); System.out.println("转换后的本地时间:" + localSdf.format(date)); } }
内容的提问来源于stack exchange,提问作者Capt Wilco
相关产品推荐
相关产品推荐

