Java Calendar setTimeZone() 方法



描述

Java Calendar setTime(TimeZone) 方法使用給定的時區設定時區。

宣告

以下是java.util.Calendar.setTime() 方法的宣告

public void setTimeZone(TimeZone value)

引數

value − 給定的時區

返回值

此方法不返回值。

異常

在當前日期的日曆例項中設定時區示例

以下示例演示了 Java Calendar setTimeZone() 方法的用法。我們使用 getInstance() 方法建立一個當前日期的日曆例項,並列印日曆例項的時區。然後,我們使用 setTimeZone() 方法更新日期的時區。最後,列印更新後的時區。

package com.tutorialspoint;

import java.util.Calendar;
import java.util.TimeZone;

public class CalendarDemo {
   public static void main(String[] args) {

      // create a calendar
      Calendar cal = Calendar.getInstance();

      // print current time zone
      String name = cal.getTimeZone().getDisplayName();
      System.out.println("Current Time Zone:" + name );
      TimeZone tz = TimeZone.getTimeZone("GMT");

      // set the time zone with the given time zone value 
      // and print it
      cal.setTimeZone(tz);
      System.out.println(cal.getTimeZone().getDisplayName());
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Current Time Zone:India Standard Time
Greenwich Mean Time

在當前日期的 GregorianCalendar 例項中設定時區示例

以下示例演示了 Java Calendar setTimeZone() 方法的用法。我們使用 GregorianCalendar() 方法建立一個當前日期的日曆例項,並列印日曆例項的時區。然後,我們使用 setTimeZone() 方法更新日期的時區。最後,列印更新後的時區。

package com.tutorialspoint;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class CalendarDemo {
   public static void main(String[] args) {

      // create a calendar
      Calendar cal = new GregorianCalendar();

      // print current time zone
      String name = cal.getTimeZone().getDisplayName();
      System.out.println("Current Time Zone:" + name );
      TimeZone tz = TimeZone.getTimeZone("GMT");

      // set the time zone with the given time zone value 
      // and print it
      cal.setTimeZone(tz);
      System.out.println(cal.getTimeZone().getDisplayName());
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Current Time Zone:India Standard Time
Greenwich Mean Time

在給定日期的 GregorianCalendar 例項中設定時區示例

以下示例演示了 Java Calendar setTimeZone() 方法的用法。我們使用 GregorianCalendar() 方法建立一個特定日期的日曆例項,並列印日曆例項的時區。然後,我們使用 setTimeZone() 方法更新日期的時區。最後,列印更新後的時區。

package com.tutorialspoint;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class CalendarDemo {
   public static void main(String[] args) {

      // create a calendar
      Calendar cal = new GregorianCalendar(2022,8,27);

      // print current time zone
      String name = cal.getTimeZone().getDisplayName();
      System.out.println("Current Time Zone:" + name );
      TimeZone tz = TimeZone.getTimeZone("GMT");

      // set the time zone with the given time zone value 
      // and print it
      cal.setTimeZone(tz);
      System.out.println(cal.getTimeZone().getDisplayName());
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Current Time Zone:India Standard Time
Greenwich Mean Time
java_util_calendar.htm
廣告