使用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 @   楼兰胡杨  阅读(1846)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
历史上的今天:
2021-09-25 SpringBoot启动类没有启动按钮,java文件变为灰色的解决策略
2021-09-25 MQ面试题|Kafka如何实现每秒上百万的高并发写入【转】
2020-09-25 ActiveMQ消息投递方式之异步投递【转】
2020-09-25 ActiveMQ消息投递方式+死信队列
2020-09-25 Spring Boot 整合ActiveMQ实现延时发现消息
2019-09-25 MySQL group_concat 介绍
2019-09-25 MySQL 取分组后每组的最新记录
点击右上角即可分享
微信分享提示