views:

65

answers:

2

Hello

If I have a method like this:

public static String convertDateTimeToString(DateTime dt) {
    return dt.getDate() + " " + dt.getTime();
}

Which takes a Datetime object of my own which contains a Java.sql.date and a Java.sql.time, what is the best way of reversing the process so that I can substring a Java.sql.date and a Java.sql.time from a string?

Or if DateTime dt is a JodaTime DateTime object?

If this can be done without reference to Java.util.date.

Thanks

Mr Morgan.

+2  A: 

Look at SimpleDateFormat class. Here's a tutorial.

You'll need something like this:

String datetimeString;
Date result;
SimpleDateFormat formatter = new SimpleDateFormat("EEE d MMM yy hh:mm:ss");
result = formatter.parse (datetimeString);
Roman
Thanks. The only issue I have with this is that Date result appears to be Java.util.date whereas I need Java.sql.date and Java.sql.time.
Mr Morgan
@Mr Morgan: but it's not a problem at all. You can create sql.Date instance easily: `java.sql.Date sqlDate = new java.sql.Date(result.getTime());`.
Roman
@Roman: Well, it seems to work as follows: String datetimeString = "2010-05-23 23:32:45"; Date result; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); result = formatter.parse (datetimeString); java.sql.Date sqlDate = new java.sql.Date(result.getTime()); java.sql.Time sqlTime = new java.sql.Time(result.getTime()); System.out.println("SQL date " + sqlDate + " " + sqlTime); Thanks.
Mr Morgan
+1  A: 

You can use the valueOf method of java.sql.Time to convert a String into a java.sql.Time, and use the valueOf method of java.sql.Date to convert a String into a java.sql.Date

Bytecode Ninja