1

I have a timestamp field which can be in any format (yyyy-MM-dd OR yyyy/MM/dd OR yyyy-MM-dd'T'HH:mm:ss ETC..) And I have no control to change it. I want to convert the incoming timestamp as it is to string so as to validate it against a RegEx.

I can find many solutions but all have a specific date format. Can this be done in generic way?

2
  • 2
    "I have a timestamp field which can be in any format" Well that's either objectively not true or incredibly weird. How do you expect to parse something that has no more predefined structure than a random collection numerals and characters? Commented Jun 20, 2018 at 10:29
  • 1
    being able to parse could mean many things... is date 01/02/03 1st of Feb '03, or 3rd of Feb '01, or 2nd of Jan '03, or 1st of Feb 1903, or 1st of Feb 0003 ? Commented Jun 20, 2018 at 10:48

1 Answer 1

2

There's no standard way to do that. You can, however, use the commons-lang library, which offers DateUtils.html#parseDate:

Parses a string representing a date by trying a variety of different parsers.
The parse will try each parse pattern in turn. A parse is only deemed successful if it parses the whole of the input string. If no parse patterns match, a ParseException is thrown.

You would then be able to use it with multiple patterns in one call:

Date d = DateUtils.parseDate("2018/06/20", 
           "yyyy-MM-dd", "yyyy/MM/dd", "yyyy-MM-dd'T'HH:mm:ss");
System.out.println(d);
//And that prints Wed Jun 20 00:00:00 SAST 2018, matching on 2nd pattern
Sign up to request clarification or add additional context in comments.

1 Comment

This looks good but thing is DateUtils.parseDate(String,String). In my case I am exposing an API which gets timestamp from the client and I need to validate if the incoming timestamp matches with yyyy-MM-dd'T'HH:mm:ss this format or not. So i do not know which format client will send (and I cannot force any restriction on this). I have a regex pattern to validate this but it again needs to convert the sent timestamp to respective string and then validaet against the regex. Not able to figure out the way out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.