📜  Java中的 LocalTime truncatedTo() 方法及示例

📅  最后修改于: 2022-05-13 01:55:05.729000             🧑  作者: Mango

Java中的 LocalTime truncatedTo() 方法及示例

LocalTime类的truncatedTo()方法用于获取此 LocalTime 在指定单位中的值。此方法采用参数 Unit,该参数是此 LocalTime 将被截断为的单位。它返回一个截断的不可变 LocalTime,其值采用指定单位。

句法:

public LocalTime truncatedTo(TemporalUnit unit)

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

返回值:该方法返回一个不可变的截断LocalTime ,根据这个时间截断时间,不为null。

异常:此方法抛出以下两个异常:

  • DateTimeException :如果无法截断。
  • UnsupportedTemporalTypeException : 如果不支持该单位

下面的程序说明了 truncatedTo() 方法:

方案一:

// 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

方案二:

// 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: Java Java.time.temporal.TemporalUnit)