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


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


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

用法:

public ZonedDateTime truncatedTo(TemporalUnit unit)

参数:此方法接受一个单个参数uint,该单位参数是该ZonedDateTime将被截断到的单位。它不能为空。


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

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

  • DateTimeException:如果无法截断。
  • UnsupportedTemporalTypeException:如果不支持该设备。

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

程序1:

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

程序2:

// 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://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#withZoneSameInstant(java.time.ZoneId)



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 ZonedDateTime truncatedTo() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。