简体   繁体   English

如何对不同格式的日期进行排序

[英]How to sort date of different formats

Below code converts a String date to a DateTime obj : 下面的代码将String日期转换为DateTime obj:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;

public class SortByDate
{
    // Date format is (mm/dd/yyyy)
    private void testSort()
    {

        List<Obj> l = new ArrayList<Obj>();

        Obj o =new Obj();
        o.date = "1/5/2015 1:37:00";
        l.add(o);
        o = new Obj();
        o.date = "1/5/2015 01:38:00";
        l.add(o);
        o = new Obj();
        o.date = "1/5/2015 01:36:00";
        l.add(o);
        o = new Obj();
        o.date = "1/5/2015";
        l.add(o);


        DateTimeFormatter dtf = org.joda.time.format.DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");

        List<DateTime> dtl = new ArrayList<DateTime>();
        for(Obj ob : l){
             dtl.add(dtf.parseDateTime(ob.date));
        }

        Collections.sort(dtl);

        for(DateTime d : dtl){
            System.out.println(d);
        }
    }

    public static void main(String args[])
    {
        new SortByDate().testSort();
    }

    private class Obj
    {
        public String date;
    }

}

But I receive exception : 但是我收到异常:

Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "1/5/2015" is too short
    at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:899)

To sort the date descending and cater for dates that do not have time set I plan to append "23:23:59" to Strings that have incorrect format, so "1/5/2015" becomes "1/5/2015 23:23:59" 为了对日期降序进行排序并满足没有时间设置的日期,我计划将“ 23:23:59”附加到格式不正确的字符串中,因此"1/5/2015"变为"1/5/2015 23:23:59"

Is there a more idiomatic approach for handling this scenario or alternative method? 是否有更惯用的方法来处理这种情况或替代方法?

"MM/dd/yyyy HH:mm:ss" is the format that your program expects. “ MM / dd / yyyy HH:mm:ss”是程序期望的格式。 Passing a string with another format "MM/dd/yyyy" is properly handled as an error. 正确地传递带有“ MM / dd / yyyy”另一种格式的字符串是错误的。

You could use regular expressions check and different dateformatter 您可以使用正则表达式检查和不同的dateformatter

 if(ob.date.matches(REG_EX_FULLDATE)){
      // use dateFormatter1
  }
 else if(ob.date.matches(REG_EX_SHORTDATE)){
     // use dateFormatter2
 } else {
       throw new RuntimeException();
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM