While some of the answers are technically correct, they are not advisable.
A few notes about Joda-Time follow.
In Joda-Time, a DateTime object truly knows its own assigned time zone. This contrasts the java.util.Date class which seems to have a time zone but does not.
Note in the example code below how we pass a time zone object to the formatter which parses the string. That time zone is used to interpret that date-time as having occurred in that time zone. So you need to think about and determine the time zone represented by that string input.
Since you have no time portion in your input string, Joda-Time assigns the first moment of the day of the specified time zone as the time-of-day. Usually this means 00:00:00
but not always, because of Daylight Saving Time (DST) or other anomalies. By the way, you can do the same to any DateTime instance by calling withTimeAtStartOfDay
.
The characters used in a formatter's pattern are similar in Joda-Time to those in java.util.Date/Calendar but not exactly the same. Carefully read the doc.
We usually use the immutable classes in Joda-Time. Rather than modify an existing Date-Time object, we call methods that create a new fresh instance based on the other object with most aspects copied except where alterations were desired. An example is the call to withZone
in last line below. Immutability helps to make Joda-Time very thread-safe, and can also make some work more clear.
You will need java.util.Date objects for use with other classes/framework that do not know about Joda-Time objects. Fortunately, it is very easy to move back and forth.
Going from a java.util.Date object (here named date
) to Joda-Time DateTime…
org.joda.time.DateTime dateTime = new DateTime( date, timeZone );
Going the other direction from Joda-Time to a java.util.Date object…
java.util.Date date = dateTime.toDate();
String input = "January 2, 2010";
java.util.Locale locale = java.util.Locale.US;
DateTimeZone timeZone = DateTimeZone.forID( "Pacific/Honolulu" ); // Arbitrarily chosen for example.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "MMMM d, yyyy" ).withZone( timeZone ).withLocale( locale );
DateTime dateTime = formatter.parseDateTime( input );
System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTime in UTC/GMT: " + dateTime.withZone( DateTimeZone.UTC ) );
When run…
dateTime: 2010-01-02T00:00:00.000-10:00
dateTime in UTC/GMT: 2010-01-02T10:00:00.000Z