1. 程式人生 > >根據現在的時區,判斷其他時區的時間,包含夏令時。

根據現在的時區,判斷其他時區的時間,包含夏令時。

 /***
     *
     * @param s 所在時區
     * @return 所在時區的時間
     */
    private String calculateTime(String s, boolean isDaylight) {
        String s1 = "空";
        //我要獲取當前的日期
        Date date = new Date();
        //設定要獲取到什麼樣的時間
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        //獲取String型別的時間
String createdate = sdf.format(date); String nowTime[] = createdate.split(":"); int now[] = new int[2]; now[0] = Integer.parseInt(nowTime[0]); now[1] = Integer.parseInt(nowTime[1]); //計算的區時=已知區時-(已知區時的時區-要計算區時的時區) if (s.contains(":")) { //如果是半個時區 判斷前面的字元是加還是減 後面的跟著變
String time[] = s.split(":"); int shiqu[] = new int[2]; shiqu[0] = Integer.parseInt(time[0]); shiqu[1] = Integer.parseInt(time[1]); if (shiqu[0] < 0) { ///這是時區是 - 的情況 例如-9:30 int hour = now[0] - (8 - shiqu[0]); int
minute = now[1] - (shiqu[1]); if (minute < 0) { hour = hour - 1; minute = 59 + minute; } if (hour < 0) { hour = 23 + hour; } //判斷是不是夏令時 if (isDaylight) { hour++; } if (minute < 10) { s1 = hour + ":0" + now[1]; } else { s1 = hour + ":" + now[1]; } } else { ///這是時區是 + 的情況 例如+9:30 int hour = now[0] - (8 - shiqu[0]); int minute = now[1] + (shiqu[1]); if (minute > 59) { hour = hour + 1; minute = minute - 59; } if (minute < 0) { hour = hour - 1; minute = 59 + minute; } if (hour > 23) { hour = hour - 23; } if (hour < 0) { hour = 23 + hour; } //判斷是不是夏令時 if (isDaylight) { hour++; } if (minute < 10) { s1 = hour + ":0" + minute; } else { s1 = hour + ":" + minute; } } } else { int time = Integer.parseInt(s); int timeHour = now[0] - (8 - time); if (timeHour < 0) { timeHour = 23 + timeHour; } //判斷是不是夏令時 if (isDaylight) { timeHour++; } if (now[1] < 10) { s1 = timeHour + ":0" + now[1]; } else { s1 = timeHour + ":" + now[1]; } } return s1; }