当前位置: 首页>>代码示例>>用法及示例精选>>正文


Java LocalTime truncatedTo()用法及代码示例

LocalTime类的truncatedTo()方法用于以指定单位获取此LocalTime的值。此方法采用参数Unit,这是该LocalTime被截断为的单位。它返回带有指定单位的值的截断的不可变LocalTime。

用法:

public LocalTime truncatedTo(TemporalUnit unit)

参数:此方法接受单个参数uint,该参数uint表示要截断的单位,不应为null。


返回值:此方法基于此时间返回不可变的,被截断的LocalTime,该时间被截断,而不是null。

异常:此方法引发以下两个异常:

  • DateTimeException:如果无法截断。
  • UnsupportedTemporalTypeException:如果不支持本机

以下示例程序旨在说明truncatedTo()方法:

程序1:

// Java program to demonstrate 
// LocalTime.truncatedTo() method 
  
import java.time.*; 
import java.time.temporal.ChronoUnit; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create a LocalTime object 
        LocalTime time 
            = LocalTime.parse("21:45:36.13"); 
  
        // print instance 
        System.out.println("LocalTime before"
                           + " truncate: "
                           + time); 
  
        // truncate to ChronoUnit.MINUTES 
        // means unit smaller than Minute 
        // will be Zero 
        LocalTime returnvalue 
            = time.truncatedTo(ChronoUnit.MINUTES); 
  
        // print result 
        System.out.println("LocalTime after "
                           + " truncate: "
                           + returnvalue); 
    } 
}
输出:
LocalTime before truncate: 21:45:36.130
LocalTime after  truncate: 21:45

程序2:

// Java program to demonstrate 
// LocalTime.truncatedTo() method 
  
import java.time.*; 
import java.time.temporal.ChronoUnit; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create a LocalTime object 
        LocalTime time 
            = LocalTime.parse("01:21:30.13"); 
  
        // print instance 
        System.out.println("LocalTime before"
                           + " truncate: "
                           + time); 
  
        // truncate to ChronoUnit.HOURS 
        // means unit smaller than Hour 
        // will be Zero 
        LocalTime returnvalue 
            = time.truncatedTo(ChronoUnit.HOURS); 
  
        // print result 
        System.out.println("LocalTime after "
                           + " truncate: "
                           + returnvalue); 
    } 
}
输出:
LocalTime before truncate: 01:21:30.130
LocalTime after  truncate: 01:00

参考: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#truncatedTo(java.time.temporal.TemporalUnit)



相关用法

注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 LocalTime truncatedTo() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文的传播和使用请遵循“署名-相同方式共享 4.0 国际 (CC BY-SA 4.0)”协议。