如何获取当前时间?不是格林威治时间,是北京时间

如何获取当前时间?不是格林威治时间,是北京时间

问题描述:

我获得到的都是格林威治时间,我就是想获取本地的北京时间。我要怎么获取?各位上个demo给我看看。我的代码是

img

还有一个问题,就是怎么把上面的 time 转换成 Date 类型?


 public static void main(String[] args) throws Exception {
        // 当前系统时区
        ZoneId currentZone = OffsetDateTime.now().getOffset();
        // 新时区,北京时间对应的时区是“GMT+8”
        ZoneId newZone = ZoneId.of("GMT+8");
        // 时区转换
        LocalDateTime localDateTime = LocalDateTime.now().atZone(currentZone).withZoneSameInstant(newZone).toLocalDateTime();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println(localDateTime.format(dtf));
    }

LocalData 获取当前日期
LocalDataTime 获取当前时间
java 1.8 新出的时间api 操作起来非常的方便,可以去看看官方文档

可以看下这两篇文章,一个是jdk8获取时间的,一个是jdk7获取时间的,你看下哪个是你想要的结果
jdk8获取时间:


jdk7获取时间: