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


Java Clock systemDefaultZone()用法及代码示例


java.time.Clock.systemDefaultZone()method是Clock类的静态方法,该方法返回一个时钟,该时钟使用最佳可用系统时钟返回时钟的当前时刻,其中返回时钟的Zone是默认时区。
如果可以使用此方法,则可以使用System.currentTimeMillis()或其他更高分辨率的时钟来实现。当需要当前日期而不需要日期或时间时,建议使用此方法。但是,如果需要日期和时间的操作,则必须使用system()方法。此方法与system(ZoneId.systemDefault())相似。从此方法返回的时钟是不可变的,线程安全的和可序列化的。

用法:

public static Clock systemDefaultZone()

返回值:此方法返回使用默认区域中最佳可用系统时钟的时钟


例:

Code:
//Clock with default zone
Clock clock=Clock.systemDefaultZone();
System.out.println(clock.instant());

Output::
2018-08-21T10:25:52.361Z

Explanation::
when you call systemDefaultZone() for Clock 
then the systemDefaultZone() method will 
return a Class Object whose Zone is default Time Zone.

下面的程序演示了java.time.Clock类的systemDefaultZone()方法:

程序1:用systemDefaultZone()创建时钟时。

此方法将时钟区域设置为默认区域。下面的程序打印日期和时间以ZonedDateTime格式显示。

// Java program to demonstrate 
// systemDefaultZone() method of Clock class 
  
import java.time.*; 
  
// create class 
public class systemDefaultZoneMethodDemo { 
  
    // Main method 
    public static void main(String[] args) 
    { 
  
        // create Clock with systemDefaultZone() method 
        Clock clock = Clock.systemDefaultZone(); 
  
        // get instant of class 
        Instant instant = clock.instant(); 
  
        // get ZonedDateTime object from 
        // instantObj to get date time 
        ZonedDateTime time = instant.atZone(clock.getZone()); 
  
        // print details of ZonedDateTime 
        System.out.println("ZonedDateTime of class"
                           + " with default Zone is "
                           + time.toString()); 
    } 
}
输出:
ZonedDateTime of class with default Zone is 2018-08-22T11:34:36.510Z[Etc/UTC]

程序2:使用getZone()为systemDefaultZone()创建的时钟打印zoneId。

// Java program to demonstrate 
// systemDefaultZone() method of Clock class 
  
import java.time.*; 
  
// create class 
public class systemDefaultZoneMethodDemo { 
  
    // Main method 
    public static void main(String[] args) 
    { 
  
        // create Clock with systemDefaultZone() method 
        Clock clock = Clock.systemDefaultZone(); 
  
        // get ZoneId of Clock 
        ZoneId zone = clock.getZone(); 
  
        // print details of ZoneId of new Clock 
        System.out.println("ZoneID of class is " + zone); 
    } 
}
输出:
ZoneID of class is Etc/UTC

参考:
https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html#systemDefaultZone-



相关用法


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