天天看点

java——时区

示例一

public static void testChange() throws ParseException {
        /*默认时区*/
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse("2019-04-17 16:05:00");
        System.out.println(simpleDateFormat.getTimeZone().toString());
        System.out.println(date.getTime());
        
        /*主动设置时区*/
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+07:00"));
        Date date1 = simpleDateFormat.parse("2019-04-17 16:05:00");
        System.out.println(date1.getTime());
    }

           

输出:

sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null]
1555488300000
1555491900000
           

示例二

public static void testZone(){
        /*通过DateFormat进行时间的换算(同一个时刻,由默认时区的时间 得到 给定的时区的时间)*/
        Date date = Calendar.getInstance().getTime();
        DateFormat df = DateFormat.getDateInstance(DateFormat.FULL);
        df.setTimeZone(TimeZone.getTimeZone("Pacific/Midway"));
        System.out.println(df.format(date));
        System.out.println();

        /*getTimeZone方法的容错性*/
        TimeZone chongqing = TimeZone.getTimeZone("Asia/Chongqing1"); /*非法的时区*/
        System.out.println(chongqing.toString());
        TimeZone chongqing1 = TimeZone.getTimeZone("Asia/Chongqing");
        System.out.println(chongqing1.toString());
        TimeZone chongqing2 = TimeZone.getTimeZone("GMT+07:00ssdsd");/*非法的时区*/
        System.out.println(chongqing2.toString());
        TimeZone chongqing3 = TimeZone.getTimeZone("GMT+07:00");
        System.out.println(chongqing3.toString());

        /*获取默认时区*/
        TimeZone zone = TimeZone.getDefault();
        System.out.println(zone.toString());
        System.out.println(System.currentTimeMillis()+TimeZone.getDefault().getDisplayName());
        /*设置时区*/
        System.setProperty("user.timezone","Pacific/Midway");
        System.out.println(System.currentTimeMillis()+System.getProperty("user.timezone"));
        System.out.println();

    }

           

输出:

2019年4月21日 星期日

sun.util.calendar.ZoneInfo[id="GMT",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
sun.util.calendar.ZoneInfo[id="Asia/Chongqing",offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null]
sun.util.calendar.ZoneInfo[id="GMT",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
sun.util.calendar.ZoneInfo[id="GMT+07:00",offset=25200000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null]
1555913150959中国标准时间
1555913150964Pacific/Midway