I'm writing some code to store metadata from uploaded images in the database. One of those fields is the photo Capture Date. The API I'm using returns the Capture Date in the String format
Sat Nov 01 20:08:07 UTC 2014
However, Joda Time throws an IllegalArgumentException when creating a DateTime
or LocalDateTime
. Conversely, java.util.Date
accepts the string formatting and creates a Date
object with no issue.
One solution is to do
Date tempDate = new Date("Sat Nov 01 20:08:07 UTC 2014");
DateTime captureDate = new DateTime(tempDate);
but this requires creating two separate objects to persist one. Given the string format above, is it possible to convince JodaTime to create a DateTime
object without an intermediary Date
initialization?
The Joda Time DateTime
and LocalDate
constructors which take Object
have documentation including:
The String formats are described by
ISODateTimeFormat.dateTimeParser()
.
The text you're providing is not in an ISO format.
Instead, you should create a DateTimeFormatter
for the format you're using, e.g. via DateTimeFormat.forPattern
, specifying the locale, time zone etc. (It's not clear from your example whether it's always going to be in UTC, or whether you need time zone handling.)
For example:
private static final DateTimeFormatter DATETIME_PARSER =
DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss 'UTC' yyyy")
.withLocale(Locale.US)
.withZoneUTC();
...
DateTime dateTime = DATETIME_PARSER.parseDateTime(text);
See more on this question at Stackoverflow