温馨提示×

simpledateformat设置时区的正确方法

小樊
108
2024-06-19 14:04:02
栏目: 编程语言

在使用SimpleDateFormat类设置时区时,可以通过以下方式指定时区:

  1. 使用时区标识符:在SimpleDateFormat的构造方法中传入指定时区的标识符,例如:"GMT+08:00"表示东八区的时区。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
  1. 使用TimeZone对象:首先创建一个TimeZone对象,然后调用SimpleDateFormat的setTimeZone方法设置时区。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
TimeZone timeZone = TimeZone.getTimeZone("GMT+08:00");
sdf.setTimeZone(timeZone);
  1. 使用Locale对象:在SimpleDateFormat的构造方法传入Locale对象时,会自动使用该Locale对象的默认时区。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

以上三种方法都可以正确设置SimpleDateFormat的时区。

0