Discuss / Java / Date有个大坑,结合DateFormat 无法实现时区转换。必须Calendar结合DateFormat才可以

Date有个大坑,结合DateFormat 无法实现时区转换。必须Calendar结合DateFormat才可以

Topic source

 // 时区转换

        System.out.println("------时区转换(可行)-------");

Calendar c= Calendar.getInstance();

        // 清除所有:

        c.clear();

        // 设置为北京时区:

        c.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));

        // 设置年月日时分秒:

        c.set(2019, 10 /* 11月 */, 20, 8, 15, 0);

        // 显示时间:

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));

        System.out.println(sdf.format(c.getTime()));

   // 时区转换

        System.out.println("---------时区转换(不好使,必须要calendar实现)--------");

        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));

        System.out.println(sdf2.format(new Date()));


  • 1

Reply