SimpleDateFormat的替代方法,用于日期解析

时间:2012-02-23 11:32:56

标签: java date timezone simpledateformat

我真的需要替代SimpleDateFormat,我正在将许多Strig日期(> 100k)从JST转换为GMT。我遇到的问题是我的代码生成了许多char [],正如我在分析时注意到的那样。对于150k日期,我使用了150MB的内存,这不是一个真正的选择。感谢。

    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
    sdf.setTimeZone(tz);
    try {
        Date theResult = sdf.parse(dateToConvert);
        SimpleDateFormat rdf = new SimpleDateFormat(resultDateFormat);
        rdf.setTimeZone(resultTz);
        return rdf.format(theResult);
    } catch (ParseException e) {
        e.printStackTrace();
    }

我不能使用Joda时间,所以这对我来说不是一个选择。 :(

5 个答案:

答案 0 :(得分:9)

使用joda-time

org.joda.time.format.DateTimeFormatter dtf = 
         org.joda.time.format.DateTimeFormat.forPattern("yyyy-MM-dd");  
    org.joda.time.DateTime date = dtf.parseDateTime(yourDate); // String like 2000-12-12
    date.withZone(yourZone); // org.joda.time.DateTimeZone

答案 1 :(得分:4)

作为一个起点,我会重用那些SimpleDateFormat个实例,而不是为每个需要转换的日期重新创建它们。

答案 2 :(得分:3)

是的,joda时间确实是一个不错的API,但是user1143825忘了设置输入timeZone。 我不能说内存性能,你必须测试它并比较结果。

这应该有效:

DateTimeFormatter sdf = DateTimeFormat.forPattern(dateFormat).withZone(tz);
try {
  DateTime theResult = sdf.parseDateTime(dateToConvert).withZone(resultTz)
  return theResult;
} catch (IllegalArgumentException e) {
  e.printStackTrace();
}

答案 3 :(得分:2)

使用java

            sample time format //31/Mar/2013:16:59:30 -0700 
            Date date = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z").parse(yourTIME);
            String time= new SimpleDateFormat("dd/MMM/yyyy, HH:mm").format(date);

使用joda库时间转换

         org.joda.time.format.DateTimeFormatter tf=org.joda.time.format.DateTimeFormat.forPattern("dd/MMM/yyyy:HH:mm:ss Z");
         org.joda.time.DateTime date = dtf.parseDateTime(time);
         String time=date.toString("dd/MMM/yyyy, HH:mm"));

这个库提高了我的代码速度性能

使用java代码14991 ms 使用joda库1668 ms

答案 4 :(得分:0)

您是否有特别的理由认为SimpleDateFormat在解析日期时效率低下?除非你的日期具有非常具体的特性,这些特性适合于某种优化,否则我会认为JDK类会做一个合理的工作。

也就是说,假设您的日期并非完全不同(不太可能有100k),您可以查看缓存 - 填充地图并传入StringDate即将到来出。这可能会大大减少所需的解析量;根据现有特性,它可能会或可能不会产生明显的加速/记忆增益。

另外,每次创建两个新的SimpleDateFormats可能非常效率低下。为什么不在加载类时创建这些实例(除非格式按行更改)?如果SDF的内部结构在第一次运行时涉及大量char[]分配,这可能会解决您自己的问题。 (请记住,奇怪的日期格式不是线程安全的,因此如果同时使用解析类,您可能需要ThreadLocal<DateFormat>