blue01
blue01

Reputation: 2095

Java Reflection - calling a a date function

I am getting a string "Date.UTC(2013,10,9,0,0,0)" from a function return. I want to construct a date out of it. something like "2013-10-09 00:00:00"

Can I use reflection to give me a timestamp from the string? Or do I have to use a substring and split based on "," and construct the date string?

Upvotes: 0

Views: 1295

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 339412

Nope, no need for reflection nor string-splitting. Let a date-time formatter do the parsing work for you.

The answer by Bohemian is correct technically. But not advisable. The bundled java.util.Date and Calendar are notoriously troublesome and should be avoided. Use either Joda-Time or the new java.time.* package found in Java 8.

Example Code

String input =  "Date.UTC(2013,10,9,0,0,0)";

DateTimeFormatter formatter = DateTimeFormat.forPattern( "'Date.UTC('yyyy,MM,dd,HH,mm,ss)" ).withZone( DateTimeZone.UTC );
DateTime dateTime = formatter.parseDateTime( input );

System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTime in India: " + dateTime.withZone( DateTimeZone.forID( "Asia/Kolkata" ) ) );

When run…

dateTime: 2013-10-09T00:00:00.000Z
dateTime in India: 2013-10-09T05:30:00.000+05:30

Upvotes: 0

Bohemian
Bohemian

Reputation: 425198

Use a SimpleDateFormat with a pattern appropriate for your input format:

Date date = new SimpleDateFormat("'Date.UTC('yyyy,MM,dd,HH,mm,ss)").parse(str);

Here's some test code:

String str = "Date.UTC(2013,10,9,0,0,0)";
Date date = new SimpleDateFormat("'Date.UTC('yyyy,MM,dd,HH,mm,ss)").parse(str);
System.out.println(date);

Output:

Wed Oct 09 00:00:00 EST 2013

Note that Date objects carry no formatting information. If you want to print a Date in a particular format, create a DateFormat for that purpose.

Upvotes: 2

dognose
dognose

Reputation: 20909

To parse a DateTime in any Format, you should have a look at http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html, especially at the method parse()

The API will serve any further information you need to accomplish your goal.

Upvotes: 0

Related Questions