1

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.

0

2 Answers 2

9

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);
Sign up to request clarification or add additional context in comments.

3 Comments

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: 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());.
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.
7

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.