How to convert calendar date to yyyy-MM-dd
format.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String date1 = format1.format(date);
Date inActiveDate = null;
try {
inActiveDate = format1.parse(date1);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
This will produce inActiveDate = Wed Sep 26 00:00:00 IST 2012
. But what I need is 2012-09-26
. My purpose is to compare this date with another date in my database using Hibernate criteria. So I need the date object in yyyy-MM-dd
format.
Best Answer
A Java
Date
is a container for the number of milliseconds since January 1, 1970, 00:00:00 GMT.When you use something like
System.out.println(date)
, Java usesDate.toString()
to print the contents.The only way to change it is to override
Date
and provide your own implementation ofDate.toString()
. Now before you fire up your IDE and try this, I wouldn't; it will only complicate matters. You are better off formatting the date to the format you want to use (or display).Java 8+
Prior to Java 8
You should be making use of the ThreeTen Backport
The following is maintained for historical purposes (as the original answer)
What you can do, is format the date.
These are actually the same date, represented differently.