Java 日历 setTimeZone()方法及示例
Calendar类中的 setTimeZone(TimeZone time_zone) 方法接受一个时区值作为参数,并修改或设置该日历所代表的时区。
语法
public void setTimeZone(TimeZone time_zone)
参数: 该方法需要一个日期类型的参数 time_zone ,指的是要设置的给定日期。
返回值: 该方法不返回任何值。
下面的程序说明了日历类的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)