📌  相关文章
📜  Java中的 ZonedDateTime truncatedTo() 方法及示例

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

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

ZonedDateTime类的truncatedTo()方法用于以指定单位返回此 ZonedDateTime 的值。此方法接受一个参数 Unit,即此 ZonedDateTime 将被截断为的 Unit。它返回一个截断的不可变 ZonedDateTime,其值采用指定单位。

句法:

public ZonedDateTime truncatedTo(TemporalUnit unit)

参数:此方法接受一个参数单位,即将此 ZonedDateTime 截断为的单位。它不应该为空。

返回值:此方法返回一个不可变的截断 ZonedDateTime ,其值采用指定单位。

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

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

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

方案一:

// Java program to demonstrate
// ZonedDateTime.truncatedTo() method
  
import java.time.*;
import java.time.temporal.ChronoUnit;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a ZonedDateTime object
        ZonedDateTime zonedDT
            = ZonedDateTime
                  .parse(
                      "2018-12-06T19:21:12.123+05:30[Asia/Calcutta]");
  
        // print ZonedDateTime
        System.out.println("ZonedDateTime before"
                           + " truncate: "
                           + zonedDT);
  
        // truncate to ChronoUnit.HOURS
        // means unit smaller than Hour
        // will be Zero
        ZonedDateTime returnvalue
            = zonedDT.truncatedTo(ChronoUnit.HOURS);
  
        // print result
        System.out.println("ZonedDateTime after "
                           + " truncate: "
                           + returnvalue);
    }
}
输出:
ZonedDateTime before truncate: 2018-12-06T19:21:12.123+05:30[Asia/Calcutta]
ZonedDateTime after  truncate: 2018-12-06T19:00+05:30[Asia/Calcutta]

方案二:

// Java program to demonstrate
// ZonedDateTime.truncatedTo() method
  
import java.time.*;
import java.time.temporal.ChronoUnit;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a ZonedDateTime object
        ZonedDateTime zonedDT
            = ZonedDateTime
                  .parse(
                      "2018-12-06T19:21:12.123+05:30[Asia/Calcutta]");
  
        // print ZonedDateTime
        System.out.println("ZonedDateTime before"
                           + " truncate: "
                           + zonedDT);
  
        // truncate to ChronoUnit.DAYS
        // means unit smaller than DAY
        // will be Zero
        ZonedDateTime returnvalue
            = zonedDT.truncatedTo(ChronoUnit.DAYS);
  
        // print result
        System.out.println("ZonedDateTime after "
                           + " truncate: "
                           + returnvalue);
    }
}
输出:
ZonedDateTime before truncate: 2018-12-06T19:21:12.123+05:30[Asia/Calcutta]
ZonedDateTime after  truncate: 2018-12-06T00:00+05:30[Asia/Calcutta]

参考: https: Java Java.time.ZoneId)