Intellipaat 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.

2 Answers

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();

}

0 votes
by (1.1k points)

In this code snippet, to achieve the "yyyy-MM-dd" format of a Calendar date, while keeping the Date object intact for Hibernate purpose comparisons, the following code can be implemented:

import java.text.SimpleDateFormat;  

import java.util.Calendar;  

import java.util.Date;  

public class DateConversionExample {  

    public static void main(String[] args) {  

        // Get the current date and add a day to it  

        Calendar cal = Calendar.getInstance();  

        cal.add(Calendar.DATE, 1);  

        Date date = cal.getTime();  

        // Change the date to yyyy-MM-dd format  

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

        String formattedDate = format1.format(date); // This gives “yyyy-MM-dd” formatted string  

        // Print the returned date string  

        System.out.println("Formatted date: " + formattedDate);  

        // Assume we will pass this date object to hibernate  

        // No converting back to date, just use 'date'  

    }  

}  

Key Points:  

  • The formattedDate will contain string formatted in “yyyy-MM-dd” pattern.  

  • Use the date for Hibernate purpose as it is without the need for parsing it again.

Related questions

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)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...