views:

49

answers:

3

Hello

Is there a straightforward way of converting a Java SQL Date from format yyyy-MM-dd to dd MMMM yyyy format?

I could convert the date to a string and then manipulate it but I'd rather leave it as a Java SQL Date. at the time I need to do this, the data has already been read from the MySQL database so I cant do the change there.

Thanks

Mr Morgan.

+3  A: 

It's not clear what you mean by a "Java SQL Date". If you mean as in java.sql.Date, then it doesn't really have a string format... it's just a number. To format it in a particular way, use something like java.text.SimpleDateFormat.

Alternatively, convert it to a Joda Time DateTime; Joda Time is a much better date and time API than the built-in one. For example, SimpleDateFormat isn't thread-safe.

(Note that a java.sql.Date has more precision than a normal java.util.Date, but it looks like you don't need that here.)

Jon Skeet
+1  A: 

Object such as java.sql.Date and java.util.Date (of which java.sql.Date is a subclass) don't have a format of themselves. You use a java.text.DateFormat object to display these objects in a specific format, and it's the DateFormat (not the Date itself) that determines the format.

For example:

Date date = ...;  // wherever you get this
DateFormat df = new SimpleDateFormat("dd MMMM yyyy");
String text = df.format(date);
System.out.println(text);

Note: When you print a Date object without using a DateFormat object, like this:

Date date = ...;
System.out.println(date);

then it will be formatted using some default format. That default format is however not a property of the Date object that you can change.

Jesper
Thanks. I have done something similar to this where the dates are written to an arraylist in a servlet and then reformatted to strings. This arraylist is then set to a session variable and processed in a JSP.
Mr Morgan
+1  A: 

If it is for presentation you can use SimpleDateFormat straight away:

package org.experiment;

import java.sql.Date;
import java.text.SimpleDateFormat;

public class Dates {
    private static SimpleDateFormat df = new SimpleDateFormat("MMMM yyyy");

    public static void main(String[] args){

        Date oneDate = new Date(new java.util.Date().getTime());
        System.out.println(df.format(oneDate));
    }

}
Miquel