Search code examples
javadatedate-formattingjava.util.calendar

How to get only date without time from calendar?


I use the following code to add one day to the calendar. However, I want to retrieve in a string only the date without the time. Is this somehow possible?

  Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE,1);
String dateandtime=calendar.getTime();

Update: Thanks for your suggestions. The similar posts suggested is too complex for a newbie like me in java. The answer provided in this question is simple. That is why I suggest this question should not be closed.


Solution

  • This might help

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, 1);
    SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
    
    String formatted = format1.format(cal.getTime());
    System.out.println(formatted);
    // Output "2020-10-19"