java联合xpath解决夏令时转换问题

在我们的项目中有这样一个需求:

从input message里得到一个GMT的标准时间,要把这个转换成CST(美国中央时区)时间,同时要考虑当地夏令时问题。

因为原先在TIBCO中有这样的函数,可以直接用,但是现在要用xslt或java实现。研究了一段时间后,终于解决。

 

首先,xpath中有这样一个函数adjust-dateTime-to-timezone(dateTime,dayTimeDuration),可以用这个函数直接将GMT时间转换成CST时间。

 

<xsl:value-of select="concat(substring(string(fn:adjust-dateTime-to-timezone(xs:dateTime($LastUpdateDate),xs:dayTimeDuration('-PT6H'))),1,19),'ZCST')"/>

 

 

然后,在java中使用SimpleTimeZone,定义好夏令时起止时间等参数,然后再用SimpleDateFormat类转换一下就可以了。

 

    //define a timezone with day light saving start and end rules.
    // DST starts:      at 2:00am in standard time
    //                  on the second Sunday in March
    // DST ends:        at 2:00am in daylight time
    //                  on the first Sunday in November
    // Save:            1 hour

    SimpleTimeZone tz = new SimpleTimeZone(-21600000, "CST", Calendar.MARCH, 8, -Calendar.SUNDAY,7200000, Calendar.NOVEMBER, 1, -Calendar.SUNDAY, 7200000, 3600000);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:SS'Z'z"); 
    sdf.setTimeZone(tz);

    if(input_lastUpdateDate!=null && !"".equalsIgnoreCase(input_lastUpdateDate))
    {

        //parse the datetime string to Date object
        Date datetime = sdf.parse(input_lastUpdateDate);

        //use the special SimpleDateFormat to format Date object, it will consider day light saving, as it uses defined timezone.
        oa_data.put("lastUpdateDate",sdf.format(datetime).substring(0, 20));

    }

 

这里的关键是定义SimpleTimeZone和SimpleDateFormat的时候,关于定义SimpleTimeZone可以参考JDK API,定义SimpleDateFormat的时候最后一定要加上z,这个表示是带时区的那个时间,不是本地时间,不然后面使用format的时候java会按本地时间进行转化。

当然完全可以用java将GMT时间转换为指定时区的时间,只是我这里必须要用xslt,所以就直接用xpath里的函数了。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值