Java中不同时区时间的转换

/**
      * 时区 时间转换方法:将传入的时间(可能为其他时区)转化成目标时区对应的时间
      * @param sourceTime 时间格式必须为:yyyy-MM-dd HH:mm:ss
      * @param sourceId 入参的时间的时区id 比如:+08:00
      * @param targetId 要转换成目标时区id 比如:+09:00
      * @param reFormat 返回格式 默认:yyyy-MM-dd HH:mm:ss
      * @return string 转化时区后的时间
      */
     public static String timeConvert(String sourceTime, String sourceId,
             String targetId,String reFormat){
         //校验入参是否合法
         if (null == sourceId || "".equals(sourceId) || null == targetId
                 || "".equals(targetId) || null == sourceTime
                 || "".equals(sourceTime)){
             return null;
         }
         
         if(StringUtil.isEmptyString(reFormat)){
        	 reFormat = "yyyy-MM-dd HH:mm:ss";
         }
         
         //校验 时间格式必须为:yyyy-MM-dd HH:mm:ss
         String reg = "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$";
         if (!sourceTime.matches(reg)){
             return null;
         }
         
         try{
             //时间格式
             SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
             //根据入参原时区id,获取对应的timezone对象
             TimeZone sourceTimeZone = TimeZone.getTimeZone("GMT"+sourceId);
             //设置SimpleDateFormat时区为原时区(否则是本地默认时区),目的:用来将字符串sourceTime转化成原时区对应的date对象
             df.setTimeZone(sourceTimeZone);
             //将字符串sourceTime转化成原时区对应的date对象
             java.util.Date sourceDate = df.parse(sourceTime);
             
             //开始转化时区:根据目标时区id设置目标TimeZone
             TimeZone targetTimeZone = TimeZone.getTimeZone("GMT"+targetId);
             //设置SimpleDateFormat时区为目标时区(否则是本地默认时区),目的:用来将字符串sourceTime转化成目标时区对应的date对象
             df.setTimeZone(targetTimeZone);
             //得到目标时间字符串
             String targetTime = df.format(sourceDate);
             
             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
             java.util.Date date = sdf.parse(targetTime);
             sdf = new SimpleDateFormat(reFormat);
             
             return sdf.format(date);
         }
         catch (ParseException e){
             e.printStackTrace();
         }
         return null;
     }

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

涛哥是个大帅比

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值