使用SimpleDateFormat获取指定时区时间

摘要:使用SimpleDateFormat把时间戳转换成指定格式的、指定时区的字符串。

  SimpleDateFormat是Java中的一个日期格式化类,继承了DateFormat,可以实现日期时间和时间字符串的相互转换。为了把时间正确地转换成时间字符串,我们需要考虑当前所在时区,而SimpleDateFormat可以通过继承的方法setTimeZone(TimeZone zone)设置时区:

 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 // 设置时区为东七区
 sdf.setTimeZone(TimeZone.getTimeZone("GMT+7:00"));

  在日期时间格式化时,通常使用的模式字符串为"yyyy-MM-dd HH:mm:ss",代码示例如下:

    public static void main(String[] args) {
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Instant now = Instant.now();
        System.out.println("与时区无瓜葛的时间戳:" + now.toEpochMilli());
        Date current = Date.from(now);
        System.out.println("本地时间:" + sdf.format(current));

        // 设置UTC时区
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        // UTC时间比北京时间少八个小时
        System.out.println("SimpleDateFormat UTC时间:" + sdf.format(current));
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+7:00"));
        System.out.println("GMT+7 时间:" + sdf.format(current));
    }

执行结果如下:

与时区无瓜葛的时间戳:1691906288129
本地时间:2023-08-13 13:58:08
SimpleDateFormat UTC时间:2023-08-13 05:58:08
GMT+7 时间:2023-08-13 12:58:08

  sdf.format(current)是把时间戳转换成指定格式的、指定时区的字符串。

posted @ 2023-09-25 07:22  楼兰胡杨  阅读(882)  评论(0编辑  收藏  举报