Reputation: 1712
Is there some simple way to parse different type of dates in java without playing with the date strings?
I have to deal with 6 different types of date:
I don't know if a date will arrive in one format or the other from the server...
thank you!
Upvotes: 1
Views: 886
Reputation: 8986
To elaborate on the stock "Use Joda-Time" answer, in Joda-Time you can create a DateTimeParser
for each of your 6 formats, then append them to a single DateTimeFormatter
.
See the accepted answer to this question: Using Joda Date & Time API to parse multiple formats
Upvotes: 1
Reputation: 31463
I don't think there's an actual "easy" way to deal with such different date formats. If you have the option to nail a "standard date format" to the server that would be the easy way.
A common approach is to build a DateParser for every 'freaky' date format that you have to deal with. Here's an example for your first date, using Joda Time:
String date1 = "16 May 2013 19:27:12 CEST";
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
.appendDayOfMonth(2)
.appendLiteral(' ')
.appendMonthOfYearShortText()
.appendLiteral(' ')
.appendYear(4, 4)
.appendLiteral(' ')
.appendHourOfDay(2)
.appendLiteral(":")
.appendMinuteOfDay(2)
.appendLiteral(":")
.appendSecondOfDay(2)
.appendLiteral(' ')
.appendLiteral("CEST")
.toFormatter();
DateTime parseDateTime = fmt.parseDateTime(date1);
System.out.println(parseDateTime);
I hope this will help you build DateParsers for the other cases. And remember - always save your dates in relation to UTC!
Upvotes: 1
Reputation: 1247
Here is the sample code, for date string like 2001-07-04T12:08:56.235-0700 we need to use following format "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date date = simpleDateFormat.parse("2001-07-04T12:08:56.235-0700");
System.out.println(date);
details are available in below mentioned link
Upvotes: 0
Reputation: 79
The best-known alternative to the standard API is Joda-Time. Also JSR 310 an improved Date/Time API for Java SE 7
Upvotes: 1
Reputation: 19294
You can iterate over all formats and try to parse, ignore the exception. If no format fits, throw an exception.
Upvotes: 4