0 votes
1 view
in Java by (10.2k 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 (46.1k 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)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...