49

In other words, I want functionality that provides Joda-Time:

today = today.withTime(0, 0, 0, 0);

but without Joda-Time, only with java.util.Date.

Methods such as .setHours() and etc. are deprecated. Is there are more correct way?

Plastic Rabbit
  • 2,459
  • 3
  • 20
  • 27
  • 1
    See http://stackoverflow.com/questions/2010284/equivalent-of-datetime-now-in-java – ide Feb 18 '11 at 21:30
  • By the way, [Joda-Time](http://www.joda.org/joda-time/) 2.3 added a method to set the time to first moment of the day: [`withTimeAtStartOfDay`](http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#withTimeAtStartOfDay()). It smartly finds the first moment for a given time zone, which is not always `00:00:00` because of Daylight Saving Time or other anomalies. That method supplants the no-longer-recommended "midnight" classes and methods. – Basil Bourque Mar 03 '14 at 01:05
  • More popular dup of this question: http://stackoverflow.com/questions/6850874/how-to-create-a-java-date-object-of-midnight-today-and-midnight-tomorrow – Vadzim Apr 02 '15 at 12:49
  • 1
    While when this question was asked in 2011 it was reasonable to use `java.util.Date` in spite of its design issues, today that class has been completely supplanted by [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). So don’t use `Date` anymore. And never again. See [the answer by Basil Bourque](https://stackoverflow.com/a/33225963/5772882). – Ole V.V. Nov 28 '18 at 08:13

8 Answers8

66
Date today = new Date();
today.setHours(0); //same for minutes and seconds

Since the methods are deprecated, you can do this with Calendar:

Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 0); // same for minutes and seconds

And if you need a Date object in the end, simply call today.getTime()

Chuck L
  • 548
  • 6
  • 21
Bozho
  • 554,002
  • 136
  • 1,025
  • 1,121
  • @Plastic Rabbit your timezones are not fine then. Use `Calendar.getInstance(utcTimezone)` for example. – Bozho Feb 18 '11 at 22:51
  • 1
    Wouldn't `today.set(Calendar.HOUR_OF_DAY, 0)` be better? `clear` sets the field to *undefined*, while `set` sets it to a defined value. – Paŭlo Ebermann Feb 18 '11 at 23:38
  • 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 Nov 27 '18 at 23:48
14
Date today = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);

DateUtils from Apache Commons-Lang. Watch out for time zone!

Tomasz Nurkiewicz
  • 311,858
  • 65
  • 665
  • 652
13

Is there are more correct way?

Yes, there is.

LocalDate.now( 
    ZoneId.of( "America/Montreal" ) 
).atStartOfDay(
    ZoneId.of( "America/Montreal" )
)

java.time

Java 8 and later now has the new java.time framework built-in. See Tutorial. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.

Examples

Some examples follow, using java.time. Note how they specify a time zone. If omitted, your JVM’s current default time zone. That default can vary, even changing at any moment during runtime, so I suggest you specify a time zone explicitly rather than rely implicitly on the default.

Here is an example of date-only, without time-of-day nor time zone.

ZoneId zonedId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zonedId );
System.out.println( "today : " + today );

today : 2015-10-19

Here is an example of getting current date-time.

ZoneId zonedId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( zonedId );
System.out.println( "zdt : " + zdt );

When run:

zdt : 2015-10-19T18:07:02.910-04:00[America/Montreal]

First Moment Of The Day

The Question asks for the date-time where the time is set to zero. This assumes the first moment of the day is always the time 00:00:00.0 but that is not always the case. Daylight Saving Time (DST) and perhaps other anomalies mean the day may begin at a different time such as 01:00.0.

Fortunately, java.time has a facility to determine the first moment of a day appropriate to a particular time zone, LocalDate::atStartOfDay. Let's see some code using the LocalDate named today and the ZoneId named zoneId from code above.

ZonedDateTime todayStart = today.atStartOfDay( zoneId );

zdt : 2015-10-19T00:00:00-04:00[America/Montreal]

Interoperability

If you must have a java.util.Date for use with classes not yet updated to work with the java.time types, convert. Call the java.util.Date.from( Instant instant ) method.

java.util.Date date = java.util.Date.from( zdt.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
10
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));

found here

Pontios
  • 1,925
  • 21
  • 26
6

If you want midnight (0:00am) for the current date, you can just use the default constructor and zero out the time portions:

Date today = new Date();
today.setHours(0); today.setMinutes(0); today.setSeconds(0);

edit: update with Calendar since those methods are deprecated

Calendar today = Calendar.getInstance();
today.clear(Calendar.HOUR); today.clear(Calendar.MINUTE); today.clear(Calendar.SECOND);
Date todayDate = today.getTime();
Daniel DiPaolo
  • 51,147
  • 13
  • 111
  • 112
  • 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 Nov 27 '18 at 23:49
1

Use this code ;

String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());

This will shown as :

Feb 5, 2013 12:39:02PM

The Holy Coder
  • 6,280
  • 8
  • 34
  • 70
1

Use this code to easy get Date & Time :

package date.time;

import java.text.SimpleDateFormat;    
import java.util.Date;

public class DateTime {

    public static void main(String[] args) {
        SimpleDateFormat dnt = new SimpleDateFormat("dd/MM/yy :: HH:mm:ss");
        Date date = new Date();
        System.out.println("Today Date & Time at Now :"+dnt.format(date));  
    } 
}
  • 1
    This Answer does not address the Question. The Question wants the time-of-day set to zero, midnight. Also, this Answer uses terrible old date-time classes that were supplanted years ago by the modern *java.time* classes. Suggesting their use in 2018 is poor advice. And a third problem, this Answer ignores the crucial issue of time zones. – Basil Bourque Jul 24 '18 at 15:58
1

Code To Get Today's date in any specific Format

You can define the desired format in SimpleDateFormat instance to get the date in that specific formate

 DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        String todaysdate = dateFormat.format(date);
         System.out.println("Today's date : " + todaysdate);

Follow below links to see the valid date format combination.

https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

CODE : To get x days ahead or Previous from Today's date, To get the past date or Future date.

For Example :

Today date : 11/27/2018

xdayFromTodaysDate = 2 to get date as 11/29/2018

xdayFromTodaysDate = -2 to get date as 11/25/2018

  public String getAniversaryDate(int xdayFromTodaysDate ){

        DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        cal.setTime(date);
        cal.add(Calendar.DAY_OF_MONTH,xdayFromTodaysDate);
        date = cal.getTime();
        String aniversaryDate = dateFormat.format(date);
        LOGGER.info("Today's date : " + todaysdate);
          return aniversaryDate;

    }

CODE : To get x days ahead or Previous from a Given date

  public String getAniversaryDate(String givendate, int xdayFromTodaysDate ){


        Calendar cal = Calendar.getInstance();
        DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        try {
            Date date = dateFormat.parse(givendate);
            cal.setTime(date);
            cal.add(Calendar.DAY_OF_MONTH,xdayFromTodaysDate);
            date = cal.getTime();
            String aniversaryDate = dateFormat.format(date);
            LOGGER.info("aniversaryDate : " + aniversaryDate);
            return aniversaryDate;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }

    }
Arpan Saini
  • 1,917
  • 18
  • 33
  • 1
    These terrible classes were outmoded years ago with the adoption of [JSR 310](https://jcp.org/en/jsr/detail?id=310), implemented in the modern [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. Suggesting the use of these legacy classes in 2018 is poor advice. – Basil Bourque Nov 27 '18 at 23:51