How to get only date without time from calendar?

1.1k views Asked by At

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.

2

There are 2 answers

1
Nooruddin Lakhani On BEST ANSWER

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"
0
Anonymous On

java.time

For a simple, reliable and up-to-date solution I recommend that you use java.time, the modern Java date and time API, for your date work.

    LocalDate today = LocalDate.now(ZoneId.of("Europe/Athens"));
    LocalDate tomorrow = today.plusDays(1);
    System.out.println(tomorrow);

When I ran this snippet just now (19 October), the output was:

2020-10-20

A LocalDate is a date without time of day (and without time zone), so it seems to me that this gives you exactly what you need, no more, no less.

For a string you may use tomorrow.toString() or use a DateTimeFormatter. Search for how to do the latter, it’s described in many places.

Link: Oracle tutorial: Date Time explaining how to use java.time.