Close

Java Date Time - LocalTime.truncatedTo() Examples

Java Date Time Java Java API 


Class:

java.time.LocalTime

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

Method:

public LocalTime truncatedTo(TemporalUnit unit)

Returns a copy of this LocalTime with the 'time' truncated according to the specified unit. The fields which are smaller than the specified unit becomes zero. This method doesn't allow truncation larger than time units.



Examples


package com.logicbig.example.localtime;

import java.time.LocalTime;
import java.time.temporal.ChronoUnit;

public class TruncatedToExample {

public static void main (String... args) {
LocalTime t = LocalTime.of(10, 30, 10, 200000);
System.out.printf("Original local time: %s%n",t);

LocalTime t2 = t.truncatedTo(ChronoUnit.NANOS);
System.out.printf("Truncated to NANOS: %s%n", t2);

t2 = t.truncatedTo(ChronoUnit.MILLIS);
System.out.printf("Truncated to MILLIS: %s%n", t2);

t2 = t.truncatedTo(ChronoUnit.SECONDS);
System.out.printf("Truncated to SECONDS: %s%n", t2);

t2 = t.truncatedTo(ChronoUnit.MINUTES);
System.out.printf("Truncated to MINUTES: %s%n", t2);

t2 = t.truncatedTo(ChronoUnit.HOURS);
System.out.printf("Truncated to HOURS: %s%n", t2);

t2 = t.truncatedTo(ChronoUnit.DAYS);
System.out.printf("Truncated to DAYS: %s%n", t2);
}

}

Output

Original local time: 10:30:10.000200
Truncated to NANOS: 10:30:10.000200
Truncated to MILLIS: 10:30:10
Truncated to SECONDS: 10:30:10
Truncated to MINUTES: 10:30
Truncated to HOURS: 10:00
Truncated to DAYS: 00:00




package com.logicbig.example.localtime;

import java.time.LocalTime;
import java.time.temporal.ChronoUnit;

public class TruncatedToExample2 {

public static void main (String... args) {
LocalTime t = LocalTime.of(10, 30, 10, 200000);
System.out.printf("Original local time: %s%n",t);

LocalTime t2 = t.truncatedTo(ChronoUnit.MONTHS);
System.out.printf("Truncated to MONTHS: %s%n", t2);
}

}

Output

Caused by: java.time.temporal.UnsupportedTemporalTypeException: Unit is too large to be used for truncation
at java.time.LocalTime.truncatedTo(LocalTime.java:955)
at com.logicbig.example.localtime.TruncatedToExample2.main(TruncatedToExample2.java:17)
... 6 more




See Also