Intelligent date / time parser for Java

后端 未结 5 1003
野性不改
野性不改 2020-12-10 14:35

Is there some intelligent date / time parser library for Java? By intelligent I mean, that I don\'t need to specify the date / time format. The API should be similar to this

相关标签:
5条回答
  • 2020-12-10 15:31

    No, there is not. What it should return on "01/02/03"? 1 Jan 2003, 3 Feb 2001, or 2 Mar 2001?

    0 讨论(0)
  • 2020-12-10 15:33

    JodaTime is excellent for manipulating date objects (e.g. date.plusDays(10))

    ...but JChronic is what you want for natural language date parsing, e.g.

    Chronic.parse("now")
    Chronic.parse("tomorrow 15:00")
    Chronic.parse("14/2/2001")
    Chronic.parse("yesterday")
    Chronic.parse("20 Jan 2010")
    

    Your question is similar to this one.

    0 讨论(0)
  • 2020-12-10 15:33

    Curious that you want to call that intelligent, just consider these:

    • Is your 1.2.2010 the same as mine?
    • What happens if the code is run on different time zones with varying locales?
    • Should it follow some well established standard or invent its own entirely?

    The answer to your question is no.

    0 讨论(0)
  • 2020-12-10 15:39

    This isn't really going to be possible, or at least reliable enough.

    For example, what date does the string 10/10/10 represent?

    0 讨论(0)
  • 2020-12-10 15:39

    You can use org.pojava. This library smart enough to detect time format

    import org.pojava.datetime.DateTime;
    import java.util.Date;
    
    public class Main{
        public static void main(String[] args){
            String input1 = "6-Jan-69";
            String input2 = "10 Apr 85 12:34:15";
            String input3 = "7/Mar/77";
    
            Date date1 = DateTime.parse(input1).toDate();
            Date date2 = DateTime.parse(input2).toDate();
            Date date3 = DateTime.parse(input3).toDate();
    
            System.out.println(date1);
            System.out.println(date2);
            System.out.println(date3);
        }
    }
    

    Output

    Mon Jan 06 00:00:00 ICT 1969
    Wed Apr 10 12:34:15 ICT 1985
    Mon Mar 07 00:00:00 ICT 1977
    
    0 讨论(0)
提交回复
热议问题