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


Java Calendar setTimeZone()用法及代码示例


Calendar类中的setTimeZone(TimeZone time_zone)方法采用“时区”值作为参数,并修改或设置由此Calendar表示的时区。

用法:

public void setTimeZone(TimeZone time_zone)

参数:该方法采用日期类型的一个参数time_zone,表示要设置的给定日期。


返回值:该方法不返回任何值。

以下示例程序旨在说明Calendar类的setTimeZone()方法的用法:
示例1:

// Java code to illustrate 
// setTime() method 
  
import java.util.*; 
  
public class Calendar_Demo { 
    public static void main(String[] args) 
    { 
  
        // Creating calendar object 
        Calendar calndr = Calendar.getInstance(); 
  
        // Displaying the current time zone 
        String tz_name = calndr.getTimeZone() 
                             .getDisplayName(); 
  
        System.out.println("The Current Time"
                           + " Zone: " + tz_name); 
  
        TimeZone time_zone 
            = TimeZone.getTimeZone("GMT"); 
  
        // Modifying the time zone 
        calndr.setTimeZone(time_zone); 
  
        // Displaying the modified zone 
        System.out.println("Modified Zone: "
                           + calndr.getTimeZone() 
                                 .getDisplayName()); 
    } 
}
输出:
The Current Time Zone: Coordinated Universal Time
Modified Zone: Greenwich Mean Time

示例2:

// Java code to illustrate 
// setTimeZone() method 
  
import java.util.*; 
  
public class Calendar_Demo { 
    public static void main(String[] args) 
    { 
  
        // Creating calendar object 
        Calendar calndr = Calendar.getInstance(); 
  
        // Displaying the current time zone 
        String tz_name = calndr.getTimeZone() 
                             .getDisplayName(); 
  
        System.out.println("The Current Time"
                           + " Zone: " + tz_name); 
  
        TimeZone time_zone 
            = TimeZone.getTimeZone("Pacific/Tahiti"); 
  
        // Modifying the time zone 
        calndr.setTimeZone(time_zone); 
  
        // Displaying the modified zone 
        System.out.println("Modified Zone: "
                           + calndr.getTimeZone() 
                                 .getDisplayName()); 
    } 
}
输出:
The Current Time Zone: Coordinated Universal Time
Modified Zone: Tahiti Time

参考: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#setTimeZone(java.util.TimeZone)



相关用法


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