关于一个时间的转换问题。由一个RFC3339时间格式的字符串转为本地时间

RFC3339时间格式的字符串转为本地的时间

          今天遇到了关于RFC3339类型的时间转换问题,在网上搜索了很多资料,发现并没有什么用处。主要是本质不正确。这个问题的解决方法要依赖于joda-time API,Joda-Time 令时间和日期值变得易于管理、操作和理解。事实上,易于使用是 Joda 的主要设计目标。其他目标包括可扩展性、完整的特性集以及对多种日历系统的支持。并且 Joda 与 JDK 是百分之百可互操作的,因此您无需替换所有 Java 代码,只需要替换执行日期/时间计算的那部分代码。

   在网上看到大多数人处理 String类型的 “2016-09-23T02:32:12.757016163Z” 的字符串用的都是SimpleDateFormat类型进行格式化,这样忽略的一个严重的问题,就是时区问题。Z代表的就是时区。

 

     YYYY = four-digit year
     MM   = two-digit month (01=January, etc.)
     DD   = two-digit day of month (01 through 31)
     hh   = two digits of hour (00 through 23) (am/pm NOT allowed)
     mm   = two digits of minute (00 through 59)
     ss   = two digits of second (00 through 59)
     s    = one or more digits representing a decimal fraction of a second
     TZD  = time zone designator (Z or +hh:mm or -hh:mm)
    

           SimpleDateFormat转换过来的时间基本都是错误的,要么是没有加时区,要么就是日期转换失败。用下边方法可以很好的解决这个问题。

首先引入需要的类:

import org.joda.time.DateTime;

import org.joda.time.DateTimeZone;

若传入的是一个string类型的数据; 例如:String rcf3339DateString =  “2016-09-23T02:32:12.757016163Z” ;

DateTime dateTime  = new DateTime(rcf3339DateString);

Long result  =  dateTime.tocalendar(Locale.getDefault()).getTimeMillis();  获取到这个时间对应的时间戳;需要什么格式的时间  使用result去转换就可以了。

若是想要将一个long类型的时间戳转换为rfc339格式的数据。可以进行以下操作。

long time = 123123123123123;

DateTime dateTime = new DateTime(time,DateTimezone.UTC) ; 第一个参数是需要转化的时间戳,第二个参数是要转化为对应时区的时间。

dateTime.toString();  即为对应时间戳的rfc339格式的时间。

 或者只处理“ 2016-09-26T02:37:23.753333Z” 格式的可以使用joda-time的ISODateTimeFormat.dateTime().parseDateTime(timestr).toDate();


版权声明:本文为houyibing930920原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。