Java 时区转换(UTC+8 到 UTC 等等)

本文介绍了一种在Java中进行时区转换的方法,通过指定时间字符串、格式、当前时区和目标时区来实现从一个时区到另一个时区的时间转换。提供了具体的Java代码示例及单元测试案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言:需要做时区转换,知道北京为UTC+8,东京为UTC+9,世界标准时间为UTC,所以下面的代码是只需要知道时区是+8还是+9还是0就可以了,不需要使用"CTT"、 "Asia/Shanghai"这种形式。

java 代码:其实是使用时区 GMT+08:00 这样的格式

/**
     * 时区转换
     * @param time 时间字符串
     * @param pattern 格式 "yyyy-MM-dd HH:mm"
     * @param nowTimeZone eg:+8,0,+9,-1 等等
     * @param targetTimeZone 同nowTimeZone
     * @return
     */
    public static String timeZoneTransfer(String time, String pattern, String nowTimeZone, String targetTimeZone) {
        if(StringUtils.isBlank(time)){
            return "";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT" + nowTimeZone));
        Date date;
        try {
            date = simpleDateFormat.parse(time);
        } catch (ParseException e) {
            logger.error("时间转换出错。", e);
            return "";
        }
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT" + targetTimeZone));
        return simpleDateFormat.format(date);
    }

单测代码:

@Test
    public void testTimeZoneTransfer(){
        String result = DateUtil.timeZoneTransfer("2018-07-03 15:43", "yyyy-MM-dd HH:mm", "+8", "0");
        Assert.assertEquals("转换错误", "2018-07-03 07:43", result);

        result = DateUtil.timeZoneTransfer("2018-07-03 15:43", "yyyy-MM-dd HH:mm", "+9", "0");
        Assert.assertEquals("转换错误", "2018-07-03 06:43", result);

        result = DateUtil.timeZoneTransfer("2018-07-03 15:43", "yyyy-MM-dd HH:mm", "-1", "0");
        Assert.assertEquals("转换错误", "2018-07-03 16:43", result);

        result = DateUtil.timeZoneTransfer("2018-07-03 15:43", "yyyy-MM-dd HH:mm", "+8", "+9");
        Assert.assertEquals("转换错误", "2018-07-03 16:43", result);

        result = DateUtil.timeZoneTransfer("2018-07-03 15:43", "yyyy-MM-dd HH:mm", "+0", "+8");
        Assert.assertEquals("转换错误", "2018-07-03 23:43", result);

        result = DateUtil.timeZoneTransfer("2018-07-03 15:43", "yyyy-MM-dd HH:mm", "+0", "0");
        Assert.assertEquals("转换错误", "2018-07-03 15:43", result);
    }

 

转载于:https://www.cnblogs.com/yuxiaole/p/9259221.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值