Java中的CST-UTC时间格式相互转换

CST-UTC有多种转换方式,本次仅记录SimpleDateFormat的转换。

1. CST转UTC

当前时间转换为UTC标准时间格式,由于时区问题所以标准时间比北京时间慢8个小时。

public static String utcDateFormat() {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    String localDateStr = simpleDateFormat.format(new Date(System.currentTimeMillis()));

    String currentTime = null;
    try {
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat1.parse(localDateStr);
        simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        currentTime = simpleDateFormat1.format(date);
    }catch (ParseException e) {
        e.printStackTrace();
    }
    return currentTime;
}

执行结果:
在这里插入图片描述

2. UTC转CST

2023-02-22T08:56:11Z转换为CST北京时间。

public static String CstDateFormat(String oldDateStr) {
    String convertTime = null;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    try {
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        //SimpleDateFormat只能格式化比自己精度长的时间,或者相同的时间精度,不能格式化比自己精度短的时间
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        convertTime = simpleDateFormat1.format(simpleDateFormat.parse(oldDateStr));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return convertTime;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值