How to Get Today's Date?
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...
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?
8 Answers
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()
Date today = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
DateUtils from Apache Commons-Lang. Watch out for time zone!
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.
Must Read
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]