6

Java 8 here. I'm trying to take the current Date (now), add one day to it, and get a new Date instance representing tomorrow that has no time component to it (only year, month & day). My best attempt:

Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 1);

Date tomorrow = calendar.getTime();

But when I print tomorrow, it contains a time component (example: Sat Jun 02 14:04:59 EDT 2018) whereas I just want it to contain zeroed-out values for hour/month/minute/etc (so: Sat Jun 02 00:00:00 EDT 2018). How can I accomplish this? At the end of the day, I just want a Date instance that represents tomorrow's date, so in pseudo code:

Date now = new Date();  // 2018-06-01
Date tomorrow = now.plus(1, DAY); // 2018-06-02
hotmeatballsoup
  • 385
  • 6
  • 58
  • 136
  • 1
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jun 03 '18 at 21:25

2 Answers2

13

Calendar.getInstance() returns a Calendar instance that contains time components, so you need to clear the time components from the Calendar instance.

Here is correct code:

    // today
    Calendar calendar = Calendar.getInstance();
    // Add 1 day -> tomorrow
    calendar.add(Calendar.DAY_OF_YEAR, 1);
    
    // Clear time components
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    // Util date tomorrow
    Date tomorrow = calendar.getTime();

Notes: you are not utilizing Java 8 Date/Time API. The below is the way if you use Java 8+

    // java 8+ Date/time API
    LocalDate today = LocalDate.now();

    LocalDate tomorrow = today.plusDays(1);

    // Java8+ tomorrow to Util tomorrow if you want
    java.util.Date tomorrowUtilDate = java.sql.Date.valueOf(tomorrow);
LHA
  • 9,398
  • 8
  • 46
  • 85
5

tl;dr

Never use java.util.Date class.

Use java.time instead.

LocalDate.now()           // Capture the current date as seen in the wall-clock time of the JVM’s current default time zone.
         .plusDays( 1 )   // Move to tomorrow’s date. Returns a fresh `LocalDate` object rather than modifying (“mutating”) the original, per immutable objects pattern.
         .toString()      // Generate a String representing this date value. Use standard ISO 8601 format: YYYY-MM-DD.

2018-06-03

Wrong type

get a new Date instance representing tomorrow that has no time component to it (only year, month & day).

You are using a date-with-time-of-day class to represent a date-only value. Square peg, round hole.

Instead, use the date-only class: LocalDate.

Avoid legacy classes

You are using terrible old date-time classes that were supplanted years ago by the industry-leading java.time classes.

I'm trying to take the current Date (now)

Get the current date by calling LocalDate.now.

LocalDate today = LocalDate.now() ;

That call implicitly applied your JVM’s current default time zone to determine the current date. A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.

LocalDate today = LocalDate.now( ZoneId.systemDefault() ) ; 

add one day to it

Easy. Call the LocalDate::plusDays method. The java.time classes use the immutable objects pattern. So rather than modify (“mutate”) the original object, a new fresh object is produced.

LocalDate tomorrow = today.plusDays( 1 ) ;

In some situations you may want to represent the amount of time to add as a an object itself. Use Period for a number of years, months, days.

Period p = Period.ofDays( 1 ) ;
LocalDate localDate = today.plus( p ) ;

Strings

To generate a String representing the value of our LocalDate, call toString if you want the standard ISO 8601 format. The standard format seems to be what you desire.

String output = tomorrow.toString() ;  // Generate String in standard ISO 8601 format, YYYY-MM-DD.

2018-01-23

You can specify a custom formatting pattern with DateTimeFormatter. Or, better, let that same class automatically localize for you using its ofLocalized… methods.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154