Use the toDateString() method to remove the time from a date, e.g. new Date(date. toDateString()) . The method returns only the date portion of a Date object, so passing the result to the Date() constructor would remove the time from the date. Copied!
time. LocalDateTime: It handles both date and time, without a time zone. It is a combination of LocalDate with LocalTime.
The Date documentation states : "Although the Date class is intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on the host environment of the Java Virtual Machine.".
The recommended way to do date/time manipulation is to use a Calendar
object:
Calendar cal = Calendar.getInstance(); // locale-specific
cal.setTime(dateObject);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long time = cal.getTimeInMillis();
Have you looked at the DateUtils truncate method in Apache Commons Lang?
Date truncatedDate = DateUtils.truncate(new Date(), Calendar.DATE);
will remove the time element.
Have you looked at Joda ? It's a much easier and more intuitive way to work with dates and times. For instance you can convert trivially between (say) LocalDateTime and LocalDate objects.
e.g. (to illustrate the API)
LocalDate date = new LocalDateTime(milliseconds).toLocalDate()
Additionally it solves some thread-safety issues with date/time formatters and is to be strongly recommended for working with any date/time issues in Java.
Just a quick update in light of the java.time classes now built into Java 8 and later.
LocalDateTime
has a truncatedTo
method that effectively addresses what you are talking about here:
LocalDateTime.now().truncatedTo(ChronoUnit.MINUTES)
This will express the current time down to minutes only:
2015-03-05T11:47
You may use a ChronoUnit
(or a TemporalUnit
) smaller than DAYS to execute the truncation (as the truncation is applied only to the time part of LocalDateTime, not to the date part).
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
date = cal.getTime();
With Joda you can easily get the expected date.
As of version 2.7 (maybe since some previous version greater than 2.2), as a commenter notes, toDateMidnight
has been deprecated in favor or the aptly named withTimeAtStartOfDay()
, making the convenient
DateTime.now().withTimeAtStartOfDay()
possible.
Benefit added of a way nicer API.
With older versions, you can do
new DateTime(new Date()).toDateMidnight().toDate()
I did the truncation with new java8 API. I faced up with one strange thing but in general it's truncate...
Instant instant = date.toInstant();
instant = instant.truncatedTo(ChronoUnit.DAYS);
date = Date.from(instant);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With