I've the Date object with the format
/107/2013 12:00:00 AM
Expected value for me:
2013-07-01
How I do this?.
I'm trying with this code
public static Date formatearFecha( Date fecha ){
String fechaString = new SimpleDateFormat("yyyy-MM-dd").format(fecha) ;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date fechaFormateada = null;
try {
fechaFormateada = df.parse(fechaString);
} catch (ParseException ex) {
Logger.getLogger(TestThings.class.getName()).log(Level.SEVERE, null, ex);
}
return fechaFormateada;
}
When I try to make a test I get this:
System.out.println( formatearFecha(myDate) );
Mon Sep 30 00:00:00 COT 2013
Update:
my problem was in sql change to java.util.Date to java.sql.Date
I solve this so:
private String formatearFecha( Date fecha ){
return new SimpleDateFormat("yyyy-MM-dd").format(fecha);
}
private java.sql.Date stringToSQLDate( String fecString ){
java.sql.Date fecFormatoDate = null;
try {
SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd", new Locale("es", "ES"));
return new java.sql.Date(sdf.parse(fecString).getTime());
} catch (ParseException ex) { }
return null;
}
And test:
stringToSQLDate( formatearFecha( myDate ) );
First of all: java.util.Date object never has a format stored in it. You can think of Date as an object containing long value of milliseconds since epoch at UTC timezone. The class has few methods, but no timezone offset, formatted pattern etc stored in it.
Secondly, following basic code can be used to format a date to yyyy-MM-dd in your machine's locale:
Similarly, you can parse a string "/107/2013 12:00:00 AM" into a date object in your machine's locale like this:
Two method above can be used to change a formatted date string from one into the other.
See the javadoc for SimpleDateFormat for more info about formatting codes.