Close

Java Date Time - OffsetDateTime.truncatedTo() Examples

Java Date Time Java Java API 


Class:

java.time.OffsetDateTime

java.lang.Objectjava.lang.Objectjava.time.OffsetDateTimejava.time.OffsetDateTimejava.time.temporal.TemporalTemporaljava.time.temporal.TemporalAdjusterTemporalAdjusterjava.lang.ComparableComparablejava.io.SerializableSerializableLogicBig

Method:

public OffsetDateTime truncatedTo(TemporalUnit unit)
Returns a copy of this OffsetDateTime with a truncated part (set to 0) specified by the provided 'unit'.

Examples


package com.logicbig.example.offsetdatetime;

import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.time.temporal.UnsupportedTemporalTypeException;

public class TruncatedToExample {

public static void main(String... args) {
OffsetDateTime d = OffsetDateTime.of(2016, 12, 15, 18,
29, 32, 15444444, ZoneOffset.ofHours(-5));
System.out.println("Original date: " + d);

for (ChronoUnit chronoUnit : ChronoUnit.values()) {
print(d, chronoUnit);
}
}

private static void print(OffsetDateTime d, ChronoUnit chronoUnit) {
try {
OffsetDateTime offsetDateTime = d.truncatedTo(chronoUnit);
System.out.printf("Truncated to %s: %s%n", chronoUnit.name(), offsetDateTime);
} catch (UnsupportedTemporalTypeException e) {
System.out.printf("The TemporalUnit not supported: %s%n", chronoUnit.name());
}
}
}

Output

Original date: 2016-12-15T18:29:32.015444444-05:00
Truncated to NANOS: 2016-12-15T18:29:32.015444444-05:00
Truncated to MICROS: 2016-12-15T18:29:32.015444-05:00
Truncated to MILLIS: 2016-12-15T18:29:32.015-05:00
Truncated to SECONDS: 2016-12-15T18:29:32-05:00
Truncated to MINUTES: 2016-12-15T18:29-05:00
Truncated to HOURS: 2016-12-15T18:00-05:00
Truncated to HALF_DAYS: 2016-12-15T12:00-05:00
Truncated to DAYS: 2016-12-15T00:00-05:00
The TemporalUnit not supported: WEEKS
The TemporalUnit not supported: MONTHS
The TemporalUnit not supported: YEARS
The TemporalUnit not supported: DECADES
The TemporalUnit not supported: CENTURIES
The TemporalUnit not supported: MILLENNIA
The TemporalUnit not supported: ERAS
The TemporalUnit not supported: FOREVER




See Also