温馨提示×

simpledateformat设置时区的正确方法

小樊
709
2024-06-19 14:04:02
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在使用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的时区。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:php date设置时区的正确方式

0