202

In my code I need to find all my things that happened today. So I need to compare against dates from today at 00:00 AM (midnight early this morning) to 12:00 PM (midnight tonight).

I know ...

Date today = new Date(); 

... gets me right now. And ...

Date beginning = new Date(0);

... gets me zero time on Jan 1, 1970. But what's an easy way to get zero time today and zero time tomorrow?


UPDATE

I did this, but surely there's an easier way?

Calendar calStart = new GregorianCalendar();
calStart.setTime(new Date());
calStart.set(Calendar.HOUR_OF_DAY, 0);
calStart.set(Calendar.MINUTE, 0);
calStart.set(Calendar.SECOND, 0);
calStart.set(Calendar.MILLISECOND, 0);
Date midnightYesterday = calStart.getTime();
            
Calendar calEnd = new GregorianCalendar();
calEnd.setTime(new Date());
calEnd.set(Calendar.DAY_OF_YEAR, calEnd.get(Calendar.DAY_OF_YEAR)+1);
calEnd.set(Calendar.HOUR_OF_DAY, 0);
calEnd.set(Calendar.MINUTE, 0);
calEnd.set(Calendar.SECOND, 0);
calEnd.set(Calendar.MILLISECOND, 0);
Date midnightTonight = calEnd.getTime();
informatik01
  • 15,174
  • 9
  • 67
  • 100
  • 3
    In my opinion Joda Time is easier, look at the end of my answer. If you want to use java.util.Date/Calendar you have to do this way, there is no easier way to do it. – timaschew Jul 27 '11 at 20:46
  • RE: timaschew comment to use Joda-Time, know that the Joda-Time project is now in maintenance mode, and advises migration to the java.time classes. – Basil Bourque Nov 08 '16 at 06:57
  • 1
    FYI, the terribly 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 Aug 17 '18 at 22:20
  • 2
    It’s seldom to see so many flawed answers to a question as to this one. I recommend [the answer by Basil Bourque](https://stackoverflow.com/a/36784346/5772882), it is correct and knowledgeable. – Ole V.V. Feb 10 '19 at 06:29

20 Answers20

386

java.util.Calendar

// today    
Calendar date = new GregorianCalendar();
// reset hour, minutes, seconds and millis
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);

// next day
date.add(Calendar.DAY_OF_MONTH, 1);

JDK 8 - java.time.LocalTime and java.time.LocalDate

LocalTime midnight = LocalTime.MIDNIGHT;
LocalDate today = LocalDate.now(ZoneId.of("Europe/Berlin"));
LocalDateTime todayMidnight = LocalDateTime.of(today, midnight);
LocalDateTime tomorrowMidnight = todayMidnight.plusDays(1);

Joda-Time

If you're using a JDK < 8, I recommend Joda Time, because the API is really nice:

DateTime date = new DateTime().toDateMidnight().toDateTime();
DateTime tomorrow = date.plusDays(1);

Since version 2.3 of Joda Time DateMidnight is deprecated, so use this:

DateTime today = new DateTime().withTimeAtStartOfDay();
DateTime tomorrow = today.plusDays(1).withTimeAtStartOfDay();

Pass a time zone if you don't want the JVM’s current default time zone.

DateTimeZone timeZone = DateTimeZone.forID("America/Montreal");
DateTime today = new DateTime(timeZone).withTimeAtStartOfDay(); // Pass time zone to constructor.
Ziem
  • 6,059
  • 7
  • 49
  • 83
timaschew
  • 15,034
  • 4
  • 56
  • 73
  • Thanks for the help, I had just updated my original question with how I was currently doing it. Thanks for the suggestion. –  Jul 27 '11 at 20:43
  • 3
    As of JodaTime 2.3, `toDateMidnight` is deprecated. See this answer for details: http://stackoverflow.com/a/19048833/363573 – Stephan Sep 27 '13 at 10:45
  • added a solution for JDK 8 – timaschew Jan 18 '15 at 14:48
  • Your top example doesn't work for me. It gives "12:03:00" for time instead of "00:00:00". Basic Java calendar sure does suck. – Amalgovinus Mar 03 '15 at 22:35
  • Which Java version are you using? For me it's working fine with JDK8 and it should also work in 6. – timaschew Mar 04 '15 at 20:59
  • 1
    @timaschew While generally correct, I suggest doing the java.time using a zoned date-time value (`ZonedDateTime`) as you did in the Joda-Time section. The `Local…` types have no time zone information – that is their entire purpose, no lose/ignore all offset and time zone details. Especially as the Question talks about using these values for comparison (maybe database queries?), a zoned date-time value is likely to be more useful. – Basil Bourque Apr 22 '16 at 02:57
  • @timaschew for a Java Calendar object you recommend setting up using new GregorianCalendar(). Others recommend using Calendar.getInstance(); Is there an advantage to your method? – AJW Oct 18 '18 at 02:28
  • 1
    @Amalgovinus Make sure to set Calendar.HOUR_OF_DAY, not Calendar.HOUR. – Oswald Aug 09 '19 at 14:07
61

For sake of completeness, if you are using Java 8 you can also use the truncatedTo method of the Instant class to get midnight in UTC.

Instant.now().truncatedTo(ChronoUnit.DAYS);

As written in the Javadoc

For example, truncating with the MINUTES unit will round down to the nearest minute, setting the seconds and nanoseconds to zero.

Hope it helps.

Basil Bourque
  • 218,480
  • 72
  • 657
  • 915
riccardo.cardin
  • 6,393
  • 1
  • 45
  • 77
  • 1
    Thanks for the hint. Getting the midnight at specified timezone becomes lengthier: `Date.from(date.toInstant().atZone(ZoneId.systemDefault()).truncatedTo(ChronoUnit.DAYS).toInstant())` – Vadzim Jun 29 '17 at 13:16
  • 5
    Beware of [difference between `truncatedTo` and `atStartOfDay`](https://stackoverflow.com/questions/29143910/java-8-date-time-get-start-of-day-from-zoneddatetime). – Vadzim Jul 22 '17 at 16:32
33

The easiest way to find a midnight:

Long time = new Date().getTime();
Date date = new Date(time - time % (24 * 60 * 60 * 1000));

Next day:

Date date = new Date(date.getTime() + 24 * 60 * 60 * 1000);
Andrei Volgin
  • 38,656
  • 5
  • 43
  • 55
  • I ran that code and got: Midnight: Thu Nov 01 19:00:00 CDT 2012 – Dave Nov 02 '12 at 18:18
  • 3
    If you did something like System.out.print(date), the system converted the date instance into the system time zone (CDT). 7pm in CDT is midnight in GMT. If you need a midnight in a selected time zone, you have to add this time zone's offset, taking DST into account. – Andrei Volgin Nov 02 '12 at 18:30
  • @Bouncner It is. There are many different 'midnight' times on Earth regardless of which method you use, but there is only one Java midnight. – Andrei Volgin Jan 20 '13 at 14:40
  • 2
    @Andrei Volgin Did not know that there is a "java midnight". ;) What I wanted to say it that this solution does imo not really help the topic creator. A calendar solution avoids ugly second-calculations and takes care of timezones (and especially day light savings times etc.) when used properly. I don't see that in your solution. – Bouncner Jan 22 '13 at 00:20
  • Hi @AndreiVolgin , I got with Date date = new Date(time+ TimeZone.getDefault().getRawOffset() - time % (24 * 60 * 60 * 1000)); – jrey May 17 '18 at 16:46
30

Remember, Date is not used to represent dates (!). To represent date you need a calendar. This:

Calendar c = new GregorianCalendar();

will create a Calendar instance representing present date in your current time zone. Now what you need is to truncate every field below day (hour, minute, second and millisecond) by setting it to 0. You now have a midnight today.

Now to get midnight next day, you need to add one day:

c.add(Calendar.DAY_OF_MONTH, 1);

Note that adding 86400 seconds or 24 hours is incorrect due to summer time that might occur in the meantime.

UPDATE: However my favourite way to deal with this problem is to use DateUtils class from Commons Lang:

Date start = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH))
Date end = DateUtils.addDays(start, 1);

It uses Calendar behind the scenes...

Tomasz Nurkiewicz
  • 311,858
  • 65
  • 665
  • 652
  • 15
    Thanks for the help. "Date is not used to represent dates" -- we'll that's pretty freakin brilliant, isn't it? ;) –  Jul 27 '11 at 20:43
  • @RobertHume To be fair, Date has been around since the first release of Java. Most things from that era are... less than perfectly thought out. Especially since Java was among the first to try the sorts of things it was trying, and there was _far_ from an agreed-upon standard for how to do it. – Fund Monica's Lawsuit Aug 28 '18 at 20:52
15

these methods will help you-

public static Date getStartOfDay(Date date) {
     Calendar calendar = Calendar.getInstance();
     calendar.setTime(date);
     calendar.set(Calendar.HOUR_OF_DAY, 0);
     calendar.set(Calendar.MINUTE, 0);
     calendar.set(Calendar.SECOND, 0);
     calendar.set(Calendar.MILLISECOND, 0);
     return calendar.getTime();
 }

and

public static Date getEndOfDay(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.HOUR_OF_DAY, 23);
    calendar.set(Calendar.MINUTE, 59);
    calendar.set(Calendar.SECOND, 59);
    calendar.set(Calendar.MILLISECOND, 999);
    return calendar.getTime();
}
9

As of JodaTime 2.3, the toDateMidnight() is deprecated.

From Upgrade from 2.2 to 2.3

    Deprecations since 2.2
    ----------------------
    - DateMidnight [#41]
     This class is flawed in concept
     The time of midnight occasionally does not occur in some time-zones
     This is a result of a daylight savings time from 00:00 to 01:00
     DateMidnight is essentially a DateTime with a time locked to midnight
     Such a concept is more generally a poor one to use, given LocalDate
     Replace DateMidnight with LocalDate
     Or replace it with DateTime, perhaps using the withTimeAtStartOfDay() method

Here is a sample code without toDateMidnight() method.

Code

DateTime todayAtMidnight = new DateTime().withTimeAtStartOfDay();
System.out.println(todayAtMidnight.toString("yyyy-MM-dd HH:mm:ss"));

Output (may be different depending on your local time zone)

2013-09-28 00:00:00
Stephan
  • 37,597
  • 55
  • 216
  • 310
  • 2
    Excellent answer. I would make the addition of passing an [`DateTimeZone`](http://www.joda.org/joda-time/apidocs/org/joda/time/DateTimeZone.html) instance to that [`DateTime`](http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html) constructor to stress the importance of specifying a time zone rather than inadvertently depending on the default: `DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );` – Basil Bourque Feb 20 '14 at 07:48
9

Other answers are correct, especially the java.time answer by arganzheng. As some mentioned, you should avoid the old java.util.Date/.Calendar classes as they are poorly designed, confusing, and troublesome. They have been supplanted by the java.time classes.

Let me add notes about strategy around handling midnight and spans of time.

Half-Open

In date-time work, spans of time are often defined using the “Half-Open” approach. In this approach the beginning is inclusive while the ending is exclusive. This solves problems and if used consistently makes reasoning about your date-time handling much easier.

One problem solved is defining the end of the day. Is the last moment of the day 23:59:59.999 (milliseconds)? Perhaps, in the java.util.Date class (from earliest Java; troublesome – avoid this class!) and in the highly successful Joda-Time library. But in other software, such as database like Postgres, the last moment will be 23:59:59.999999 (microseconds). But in other software such as the java.time framework (built into Java 8 and later, successor to Joda-Time) and in some database such the H2 Database, the last moment might be 23:59.59.999999999 (nanoseconds). Rather than splitting hairs, think in terms of first moment only, not last moment.

In Half-Open, a day runs from the first moment of one day and goes up to but does not include the first moment of the following day. So rather than think like this:

…from today at 00:00am (midnight early this morning) to 12:00pm (midnight tonight).

…think like this…

from first moment of today running up to but not including first moment of tomorrow:
( >= 00:00:00.0 today AND < 00:00:00.0 tomorrow )

In database work, this approach means not using the BETWEEN operator in SQL.

Start of day

Furthermore, the first moment of the day is not always the time-of-day 00:00:00.0. Daylight Saving Time (DST) in some time zones, and possibly other anomalies, can mean a different time starts the day.

So let the java.time classes do the work of determining the start of a day with a call to LocalDate::atStartOfDay( ZoneId ). So we have to detour through LocalDate and back to ZonedDateTime as you can see in this example code.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now( zoneId );
ZonedDateTime todayStart = now.toLocalDate().atStartOfDay( zoneId );
ZonedDateTime tomorrowStart = todayStart.plusDays( 1 );

Note the passing of the optional ZoneId. If omitted your JVM’s current default time zone is applied implicitly. Better to be explicit.

Time zone is crucial to date-time work. The Question and some other Answers are potentially flawed because the do not consciously handle time zone.

Convert

If you must use a java.util.Date or .Calendar, look for new conversion methods added to those old classes.

java.util.Date utilDate = java.util.Date.from( todayStart.toInstant() );
java.util.GregorianCalendar gregCal = java.util.GregorianCalendar.from( todayStart );

Span of time

By the way, if you are doing much work with spans of time take a look at:

  • Duration
  • Period
  • Interval
    The Interval class is found in the ThreeTen-Extra project, an extension to the java.time framework. This project is the proving ground for possible future additions to java.time.
    Interval todayMontreal = Interval.of( todayStart.toInstant() , tomorrowStart.toInstant() );

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
  • 218,480
  • 72
  • 657
  • 915
6

java.time

If you are using Java 8 and later, you can try the java.time package (Tutorial):

LocalDate tomorrow = LocalDate.now().plusDays(1);
Date endDate = Date.from(tomorrow.atStartOfDay(ZoneId.systemDefault()).toInstant());
Basil Bourque
  • 218,480
  • 72
  • 657
  • 915
arganzheng
  • 1,103
  • 13
  • 18
  • 2
    Good answer. I would suggest specifying the desired/expected time zone. The JVM’s current default time zone can vary by OS settings, changing computers, or any app in any thread of the JVM changing the default at any moment during runtime. – Basil Bourque Dec 10 '15 at 00:30
5

This appears to be an option:

DateFormat justDay = new SimpleDateFormat("yyyyMMdd");
Date thisMorningMidnight = justDay.parse(justDay.format(new Date()));

to add a day to it, either

Date tomorrow = new Date(thisMorningMidnight.getTime() + 24 * 60 * 60 * 1000);

or

Calendar c = Calendar.getInstance();
c.setTime(thisMorningMidnight);
c.add(Calendar.DATE, 1);
Date tomorrowFromCalendar = c.getTime();

I have a hunch the latter is preferred in case of something weird like daylight savings causing adding 24 hours to not be enough (see https://stackoverflow.com/a/4336131/32453 and its other answers).

Community
  • 1
  • 1
rogerdpack
  • 50,731
  • 31
  • 212
  • 332
  • I have a date and time of day represented as a long in my sqlite database. I need to get a long for the beginning of the next day. Can I still use a Date object with my long rather than with the SimpleDateFormat method that you use above? – AJW Oct 18 '18 at 02:20
  • 1
    As long as it's the right milliseconds you can pass it as a constructor: https://docs.oracle.com/javase/7/docs/api/java/util/Date.html#Date(long) – rogerdpack Oct 18 '18 at 03:35
3

JDK8 - Java Time Module way:

LocalDateTime todayMidnight = LocalDate.now().atStartOfDay();

Also work:

LocalDateTime todayMidnight = LocalDateTime.now().with(LocalTime.MIDNIGHT);

  • It’s usually better to use `ZonedDateTime` than `LocalDateTime`. And in any case I suggest specifying time zone, even if it is just `LocalDate.now(ZoneId.systemDefault())`. In any case thanks for mentioning java.time, the modern Java date and time API, it’s the good choice for the job. – Ole V.V. Dec 13 '20 at 19:40
1

Using apache commons..

//For midnight today 
Date today = new Date(); 
DateUtils.truncate(today, Calendar.DATE);

//For midnight tomorrow   
Date tomorrow = DateUtils.addDays(today, 1); 
DateUtils.truncate(tomorrow, Calendar.DATE);
joe4java
  • 39
  • 8
  • FYI, the terribly 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 Nov 16 '18 at 06:36
  • @BasilBourque Agreed for Java 8. But if OP is using Java 7, I guess still that would work. – joe4java Nov 16 '18 at 17:07
  • Nearly all of the *java.time* functionality is available for Java 6 & 7 in the *ThreeTen-Backport* project with virtually identical API. Further adapted for Android <26 in the *ThreeTenABP* project. So no need to ever again use those wretched old date-time classes. – Basil Bourque Nov 16 '18 at 17:19
1

I did this differently than everyone else here did. I'm new to Java, so maybe my solution is poor.

Date now = new Date();
Date midnightToday = new Date(now.getYear(), now.getMonth(), now.getDate());

I'm not sure this works yet, but either way, I'd appreciate any feedback on this solution.

I'm confused by the statement above that you can calculate tomorrow by calling:

c.add(Calendar.DAY_OF_MONTH, 1);

If you add 1 to the day of the month and it's the 31st day, don't you get the 32nd day of the month?

Why are times/dates not all based on UTC in Java? I would think Timezones should only be needed when used with i/o, but internally should always be used in UTC. However, the classes seem to include Timezone info which seems not only wasteful, but prone to coding errors.

Paritosh
  • 2,029
  • 3
  • 23
  • 37
Mitch
  • 1,671
  • 3
  • 25
  • 38
  • 2
    Hi Mitch. I think your solution works, but it looks like that Date constructor is deprecated. The Java folks deprecated most of the original Date related methods a while back and replaced them with newer Calendar related methods. Personally I don't see how it's an improvement, but it's frowned on to use deprecated methods. Thanks! –  Sep 01 '11 at 18:44
  • Sad about the deprecation. It seems much cleaner to me to specify the year, month and date rather than clearing the hour, minute, second and millisecs. Clearing these relies on millisecs being the finest granularity of the Date class, while my solution doesn't. My solution is also shorter and clearer. Being new to Java makes me really appreciate just how clean, easy and efficient C++ is when it comes to using dates and times. – Mitch Sep 01 '11 at 23:58
  • @Mitch In my experience, the most recent language you're learning is always perceived as the most complicated. – ArtOfWarfare Oct 31 '12 at 13:45
  • FYI: these bloody awful old date-time classes are now legacy, supplanted by the modern java.time classes. – Basil Bourque Jun 28 '17 at 17:54
0

Apache Commons Lang

DateUtils.isSameDay(date1, date2)

http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/DateUtils.html#isSameDay(java.util.Date, java.util.Date)

Anders B
  • 2,923
  • 1
  • 23
  • 15
0

The simplest way with JodaTime

DateMidnight date = DateMidnight.now();

  • 2
    No. The "midnight"-related classes and methods in Joda-Time have all been deprecated. They were based on a flawed concept. The first moment of the day is not always `00:00:00.000`. Instead use the new [`withTimeAtStartOfDay`](http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#withTimeAtStartOfDay()) method. Update to the current version 2.4 of Joda-Time and read the release notes. Example: `DateTime today = DateTime.now( DateTimeZone.forID( "America/Montreal" ) ).withTimeAtStartOfDay();` – Basil Bourque Aug 19 '14 at 15:08
0

Because of one day is 24 * 60 * 60 * 1000 ms, the midnight of this day can be calculate as...

long now = System.currentTimeMillis();
long delta = now % 24 * 60 * 60 * 1000;
long midnight = now - delta;
Date midnightDate = new Date(midnight);`
noufalcep
  • 2,996
  • 15
  • 28
  • 46
lshu
  • 9
  • 2
  • 1
    This code only applies to UTC and no other time zone, and ignores anomalies such as Daylight Saving Time. Furthermore, roll-your-own date-time solutions is unwise as this is a surprisingly tricky topic. Use the excellent java.time classes instead. – Basil Bourque Oct 31 '16 at 05:41
0

Pretty much as the answers before, but nobody mentioned AM_PM parameter:

    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    cal.set(Calendar.AM_PM, Calendar.AM);
Montaser
  • 59
  • 5
  • 1
    The troublesome `Calendar` class was supplanted years ago by the *java.time* classes, specifically [`ZonedDateTime`](https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html). – Basil Bourque Apr 08 '18 at 16:44
0
Date now= new Date();
// Today midnight
Date todayMidnight = new Date(endTime.getTime() -endTime.getTime()%DateUtils.MILLIS_PER_DAY);

// tomorrow midnight
Date tomorrowMidnight = new Date(endTime.getTime() -endTime.getTime()%DateUtils.MILLIS_PER_DAY + DateUtils.MILLIS_PER_DAY);
gzg_55
  • 51
  • 1
  • 2
  • This only works for UTC, and fails to address time zones. Also, the terrible `Date` class was supplanted years ago by `java.time.Instant`. Avoid using `Date` nowadays. – Basil Bourque Aug 14 '18 at 14:21
-1

I know this is very old post. I thought to share my knowledge here !

For the date Mid night today with exact Time zone you can use following

public static Date getCurrentDateWithMidnightTS(){

    return new Date(System.currentTimeMillis() - (System.currentTimeMillis()%(1000*60*60*24)) - (1000*60 * 330));
}

Where (1000*60 * 330) is being subtracted i.e. actually related to time zone for example Indian time zone i.e. kolkata differs +5:30hrs from actual . So subtracting that with converting into milliseconds.

So change last substracted number according to you. I m creating a product i.e. only based in India So just used specific timestamp.

Rajeev
  • 1,381
  • 1
  • 18
  • 31
  • 1
    Why would you suggest this instead of the accepted answer? Rolling your date-time values is risky in general. In particular this code is hard-coded to a single time zone's current offset forever. There is no accounting for Daylight Saving Time or other anomalies. I see only downsides with no added value. – Basil Bourque Nov 28 '14 at 19:05
  • @Basil of course I accept answer and yes I mentioned there for hard coded value . This is helpful only in case of you are working on a specific time zone . – Rajeev Nov 29 '14 at 07:46
-1
Date todayMidnightUTC = java.sql.Date.valueOf(LocalDate.now());
Date tomorrowMidnightUTC = java.sql.Date.valueOf(LocalDate.now().plusDays(1));
Date anyMidnightLocal = java.sql.Date.valueOf(LocalDate.from(dateTime.toInstant().atZone(ZoneId.systemDefault())));

But beware that java.sql.Date.toInstant() always throws UnsupportedOperationException.

Via LocalDate to java.util.Date and vice versa simpliest conversion?

Vadzim
  • 21,258
  • 10
  • 119
  • 142
  • *Not* a good Answer. You are mixing the use of the modern java.time with the old legacy classes they supplant. And specifically you use the java.sql date-time classes that should only be used for exchanging data with a database whose driver has not yet been updated to deal directly with the java.time classes, never to be used for business logic. Yet another problem is that you ignore the crucial issue of time zone. – Basil Bourque Jun 28 '17 at 17:58
  • @BasilBourque, thanks for the critique. Using one legacy class that isn't marked as deprecated to obtain another legacy class instance is quite safe. The timezone issue is more important. I decided to stick with riccardo's [answer](https://stackoverflow.com/a/40467674/603516) after all. – Vadzim Jun 29 '17 at 13:21
-1

Old fashioned way..

private static Date getDateWithMidnight(){
    long dateInMillis = new Date().getTime();
    return new Date(dateInMillis - dateInMillis%(1000*60*60*24) - TimeZone.getDefault().getOffset(dateInMillis));
}
  • That troublesome class was supplanted years ago by the *java.time.Instant* class. No need to ever use `Date`. – Basil Bourque Aug 17 '18 at 16:08
  • That `Date` class is always in UTC. So you are ignoring the issue of the desired/expected time zone. For example, a new day dawns in Kolkata India many hours earlier than in UTC, and hours later than UTC in Montréal Québec. – Basil Bourque Aug 17 '18 at 16:11