I want to set the minutes and seconds of a date to 0, but I see that those methods are deprecated
Date yesterday = Date.from(Instant.now().minus(24, ChronoUnit.HOURS));
yesterday.setMinutes(0);
yesterday.setSeconds(0);
I want to set the minutes and seconds of a date to 0, but I see that those methods are deprecated
Date yesterday = Date.from(Instant.now().minus(24, ChronoUnit.HOURS));
yesterday.setMinutes(0);
yesterday.setSeconds(0);
ZonedDateTime yesterday = ZonedDateTime.now(ZoneId.of("Europe/Madrid"))
.minusDays(1)
.truncatedTo(ChronoUnit.HOURS);
System.out.println("Yesterday with minutes and seconds set to 0: " + yesterday);
Running just now gave
Yesterday with minutes and seconds set to 0: 2019-03-17T23:00+01:00[Europe/Madrid]
If you intended “yesterday at the same time”, that’s not always 24 hours ago. Due to summer time (DST) and other anomalies, a day may be for example 23, 23,5 or 25 hours.
The ZonedDateTime
class of java.time, the modern Java date and time API, takes the time anomalies in your time zone into account. So when you subtract a day, you do get the same time yesterday, if that time exists at all.
.truncatedTo(ChronoUnit.HOURS)
sets minutes, seconds and fraction of second to 0 in the time zone in question.
You were trying to use the Date
class, but in Java 8 you should not do that. It’s poorly designed and long outdated. I find java.time so much nicer to work with.
You may need a Date
for a legacy API that you cannot change or cannot afford to change just now. In that case convert only in the last moment:
Instant yesterdayInstant = yesterday.toInstant();
Date yesterdayDate = Date.from(yesterdayInstant);
System.out.println("As old-fashoined Date: " + yesterdayDate);
In my time zone (Europe/Copenhagen, currently agrees with Europe/Madrid) I got
As old-fashoined Date: Sun Mar 17 23:00:00 CET 2019
Oracle Tutorial: Date Time explaining how to use java.time.