Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.9k points)

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.

1 Answer

0 votes
by (46k points)

Your code is wrong. No point of parsing date and keep that as Date object.

You can format the calender date object when you want to display and keep that as a string.

Calendar cal = Calendar.getInstance();

cal.add(Calendar.DATE, 1);

Date date = cal.getTime();             

SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");          

String inActiveDate = null;

try {

    inActiveDate = format1.format(date);

    System.out.println(inActiveDate );

} catch (ParseException e1) {

    // TODO Auto-generated catch block

    e1.printStackTrace();

}

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 29, 2019 in Java by Suresh (3.4k points)
0 votes
1 answer
asked Jan 28, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
asked Dec 4, 2020 in SQL by Appu (6.1k points)

Browse Categories

...