-2

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);
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Nuñito Calzada
  • 4,394
  • 47
  • 174
  • 301
  • 3
    You are using the `Date` class, but in Java 8 you should not do that. It’s poorly designed and long outdated. Stick with `Instant` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). And use `yesterday = yesterday.truncatedTo(ChronoUnit.HOURS);`. – Ole V.V. Mar 18 '19 at 21:28

1 Answers1

2

TL;DR

    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]

Define yesterday

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.

java.time

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.

If you indispensably need an old-fashioned Date

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

Link

Oracle Tutorial: Date Time explaining how to use java.time.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161