Get the midnight time in milliseels for the given time in millise

What is the proposed way to get midnight in UTC for a given period of time in milliseconds? I tried the following, which seems to work, wondering if there is a better way to do the same.

 public long toUtcMidnight(final Long date) {
    return LocalDateTime.ofInstant(Instant.ofEpochMilli(date), ZoneId.of("UTC"))
            .toLocalDate()
            .atStartOfDay()
            .toInstant(ZoneOffset.UTC)
            .toEpochMilli();
    }

We could use Joda time for this, but for this I only want to use the java 8 date library.

+4
source share
5 answers

You can trim Instantup to a day. From javadoc

Truncation of the moment returns a copy of the original with fields less than the specified unit set to zero.

Using ChronoUnit.Days, you will get zero hours, minutes, seconds, milliseconds.

for example

Instant.ofEpochMilli(date).truncatedTo(ChronoUnit.DAYS).toEpochMilli();
+4

, - , Calendar?

 public long toUtcMidnight(long date) {
      Calendar cal = Calendar.getInstance();
      cal.setTimeInMillis(date);
      cal.setTimeZone(TimeZone.getTimeZone("UTC"));
      cal.set(Calendar.HOUR_OF_DAY, 0);
      cal.set(Calendar.MINUTE, 0);
      cal.set(Calendar.SECOND, 0);
      cal.set(Calendar.MILLISECOND, 0);
      return cal.getTimeInMillis();   
 }
0

UTC millis/86400_000 * 86400_000;

(int) * msecs/day msec.

, , .

0

, , .

atStartOfDay, . 00:00:00.0. UTC.

ZonedDateTime midnightUtc = LocalDate.now( ZoneOffset.UTC ).atStartOfDay( ZoneOffset.UTC );
long millisecondsSinceEpoch = midnightUtc.toInstant().toEpochMilli();

.

System.out.println( "midnightUtc: " + midnightUtc );
System.out.println( "millisecondsSinceEpoch: " + millisecondsSinceEpoch );

.

midnightUtc: 2015-09-26T00: 00Z

SinceEpoch: 1443225600000

0

, :

long fullMsecs = System.currentTimeMillis();
long days = TimeUnit.MILLISECONDS.toDays(msecs);
long truncatedMsecs = TimeUnit.DAYS.toMillis(days);

:

long msecs = TimeUnit.DAYS.toMillis(
                TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis()));
0

Source: https://habr.com/ru/post/1609029/


All Articles