Java之时间格式转换

目的:将UTC时间转换为北京时间

Java提供了至少两种时间转换方式,
分别是  SimpleDateFormat   和   DateTimeFormatter

这两者的区别是:

	第一种线程不安全,因此每次使用都需要 new 一个新的对象,执行效率较低。
		在多线程的场景下如果定义为静态变量被公共使用则会有线程不安全问题;
    
    第二种是Java8新出的功能,避免了线程不安全问题,可以被当做静态变量公共使用;

现使用上述两种方法实现UTC时间转UTC8(北京、上海时间)
上代码

方法1

	Date dateUTC = null;
    //定义UTC时间格式
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

    try {
  	    //解析字符串UTC时间Date类型
        dateUTC = sdf.parse(timestamp);
    }catch (ParseException ignored) {
    log.error("UTC time parse failed, UTC time is {}", timestamp);
    }
  
    //定义中国上海地区时间格式
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
    return simpleDateFormat.format(dateUTC);

输入 timeStamp为字符串, 输出也为字符串
这里GMT == UTC

方法2

	//UTC时间格式
	public static final DateTimeFormatter timeFormatForUTC = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
    //上海时间格式
    public static final DateTimeFormatter timeFormatForChina = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


	public static String conversionTimeFormat(String timestamp) {
        LocalDateTime dateUTC = LocalDateTime.parse(timestamp, timeFormatForUTC);
        ZonedDateTime dateZoneForUTC = ZonedDateTime.of(dateUTC, ZoneId.of("GMT"));
        return timeFormatForChina.format(dateZoneForUTC.withZoneSameInstant(ZoneId.of("Asia/Shanghai")));
    }

完成
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值