Tiny
Tiny

Reputation: 27889

Change the date time format of an existing DateTime instance of Joda

I have two date fields. A user can choose a date from a jQuery date-time picker which is then converted into the UTC format (via a custom property editor of Spring) and populated into a Java bean upon the submission of the form.

These DateTime instances from the Java bean are retrieved by org.apache.commons.beanutils.PropertyUtils via reflection like,

final Object object1 = PropertyUtils.getProperty(beanObject, firstDate);
final Object object2 = PropertyUtils.getProperty(beanObject, secondDate);

These objects are type-cast to DateTime.

if(object1!=null && object2!=null)
{
    final DateTime startDate=((DateTime)object1).withZone(DateTimeZone.forID("Asia/Kolkata"));
    final DateTime endDate=((DateTime)object2).withZone(DateTimeZone.forID("Asia/Kolkata"));

    System.out.println("startDate = "+startDate+"\nendDate = "+endDate);
}

This produces the following output.

startDate = 2013-02-17T22:45:59.000+05:30
endDate = 2013-02-18T22:46:00.000+05:30

I need to conver these dates into this format - dd-MMM-yyyy HH:mm:ss

The following approach which I have tried doesn't work.

DateTime newStartDate=new DateTime(startDate.toString("dd-MMM-yyyy HH:mm:ss"));
DateTime newEndDate=new DateTime(startDate.toString("dd-MMM-yyyy HH:mm:ss"));

System.out.println("newStartDate = "+newStartDate+"\nnewEndDate = "+newEndDate);

It gives the following exception.

java.lang.IllegalArgumentException: Invalid format: "17-Feb-2013 22:45:59" is malformed at "-Feb-2013 22:45:59"

So how to convert these dates into the required format?

Upvotes: 1

Views: 725

Answers (1)

JB Nizet
JB Nizet

Reputation: 691845

A DateTime doesn't have any format. It has a value, which is a number of milliseconds since 1st Jan. 1970, and a chronology. It's only when you transform a DateTime to a String that you need to choose a format. And you know how to do that already, since you're doing it in your question.

So what you're trying to do just doesn't make sense.

Upvotes: 1

Related Questions