當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。