Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect the given date format using java

Tags:

java

localdate

I have a method that gets a string and change that to a particular date format but the thing is the date will be any format For Example

16 July 2012

March 20 2012

2012 March 20

So I need to detect the string is in which file format.

I use the below code to test it but I get exception if the file format changes.

private String getUpdatedDate(String updated) {
        Date date;
        String formatedDate = null;
        try {
            date = new SimpleDateFormat("d MMMM yyyy", Locale.ENGLISH)
                    .parse(updated);
            formatedDate = getDateFormat().format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return formatedDate;
    }
like image 315
Ramesh Avatar asked Jul 03 '12 11:07

Ramesh


3 Answers

Perhaps the easiest solution is to build a collection of date formats you can reasonably expect, and then try the input against each one in turn.

You may want to flag ambiguous inputs e.g. is 2012/5/6 the 5th June or 6th May ?

like image 133
Brian Agnew Avatar answered Oct 21 '22 23:10

Brian Agnew


BalusC wrote a simple DateUtil which serves for many cases. You may need to extend this to satisfy your requirements.

Here is the link: https://balusc.omnifaces.org/2007/09/dateutil.html

and the method you need to look for determineDateFormat()

like image 22
RP- Avatar answered Oct 21 '22 23:10

RP-


If you're using Joda Time (awesome library btw) you can do this quite easily:

DateTimeParser[] dateParsers = { 
        DateTimeFormat.forPattern("yyyy-MM-dd HH").getParser(),
        DateTimeFormat.forPattern("yyyy-MM-dd").getParser() };
DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, dateParsers).toFormatter();

DateTime date1 = formatter.parseDateTime("2012-07-03");
DateTime date2 = formatter.parseDateTime("2012-07-03 01");
like image 3
Andreas Johansson Avatar answered Oct 21 '22 23:10

Andreas Johansson