Reputation: 57
I want to store today's date in the format yyyy-mm-dd. before storing I have took today's date,formatted it and again parse the formatted string to date. It gives the output date in a different format other than what I want. How can i get the date, format it in 'yyyy-mm-dd' and again convert it into date and want the output in the format 'yyyy-mm-dd'.Please find the below code and tell me where I am wrong
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = new java.util.Date();
java.util.Date date1;
String datestring=dateFormat.format(date);
try {
date1=dateFormat.parse(datestring);
System.out.print(date1);
} catch (ParseException ex) {
Logger.getLogger(accordcclass.class.getName()).log(Level.SEVERE, null, ex);
}
The output for the above code I get is Thu Mar 07 00:00:00 GMT 2013. But I want the output as 2013-01-07
Upvotes: 0
Views: 27290
Reputation: 61
I had the same problem, this is what I did:
DateFormat inputDateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
DateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
System.out.println(outputDateFormat.format(inputDateFormat.parse("09-SEP-2013 10:00")));
That way I can parse the date in the original format and output it in the database compatible format.
There is the posibility of using PreparedStatement as someone mentiones before but I don't want to.
Upvotes: 6
Reputation: 86391
You're using the DateFormat to format and reparse.
You don't need to re-parse. Simply use the DateFormat only to format.
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = new java.util.Date();
String datestring=dateFormat.format(date);
System.out.println( datestring );
Upvotes: 0
Reputation: 2610
Don't use a Date
object to print, use directly your datestring
variable. Using a Date
will call toString
which will be formatted using the Locale
.
Edit : Adding that if you want to store your Date
variable with a format, it doesn't work that way. A Date
doesn't hold a format, it just represents the time. How you show it in a GUI, console or anywhere else is where you need to specify a format if you want it to differ from the current Locale
format.
Upvotes: 5