Java/Development Class/TimeZone

Материал из Java эксперт
Перейти к: навигация, поиск

Converting Times Between Time Zones

   
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a Calendar object with the local time zone
    Calendar local = new GregorianCalendar();
    local.set(Calendar.HOUR_OF_DAY, 10); // 0..23
    local.set(Calendar.MINUTE, 0);
    local.set(Calendar.SECOND, 0);
  }
}





Convert the date to the given timezone

  
/*
 * Funambol is a mobile platform developed by Funambol, Inc. 
 * Copyright (C) 2003 - 2007 Funambol, Inc.
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission 
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE 
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Affero General Public License 
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 * 
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite 
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.ru.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably 
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * Utility class for date manipulation.
 * This class gives a simple interface for common Date, Calendar and Timezone
 * operations.
 * It is possible to apply subsequent transformations to an initial date, and
 * retrieve the changed Date object at any point.
 *
 */
public class DateUtil {
    
    //-------------------------------------------------------------- Attributes
    private Calendar cal;
    
    //------------------------------------------------------------ Constructors
    
    /** Inizialize a new instance with the current date */
    public DateUtil() {
        this(new Date());
    }
    
    /** Inizialize a new instance with the given date */
    public DateUtil(Date d) {
        cal = Calendar.getInstance();
        cal.setTime(d);
    }
    
    //---------------------------------------------------------- Public methods
    
    /** Set a new time */
    public void setTime(Date d) {
        cal.setTime(d);
    }
    
    /** Get the current time */
    public Date getTime() {
        return cal.getTime();
    }
    
    /** Get the current TimeZone */
    public String getTZ() {
        return cal.getTimeZone().getID();
    }
    
    /**
     * Convert the time to the midnight of the currently set date.
     * The internal date is changed after this call.
     *
     * @return a reference to this DateUtil, for concatenation.
     */
    public DateUtil toMidnight() {
        
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND,0);
        
        return this;
    }
    
    /**
     * Make the date go back of the specified amount of days
     * The internal date is changed after this call.
     *
     * @return a reference to this DateUtil, for concatenation.
     */
    public DateUtil removeDays(int days) {
        
        Date d = cal.getTime();
        long time = d.getTime();
        time -= days * 24 * 3600 * 1000;
        d.setTime(time);
        cal.setTime(d);
        
        return this;
    }
    
    /**
     * Make the date go forward of the specified amount of minutes
     * The internal date is changed after this call.
     *
     * @return a reference to this DateUtil, for concatenation.
     */
    public DateUtil addMinutes(int minutes) {
        Date d = cal.getTime();
        long time = d.getTime();
        time += minutes * 60 * 1000;
        d.setTime(time);
        cal.setTime(d);
        
        return this;
    }
    
    /**
     * Convert the date to GMT. The internal date is changed
     *
     * @return a reference to this DateUtil, for concatenation.
     */
    public DateUtil toGMT() {
        return toTZ("GMT");
    }
    
    /**
     * Convert the date to the given timezone. The internal date is changed.
     *
     * @param tz The name of the timezone to set
     *
     * @return a reference to this DateUtil, for concatenation.
     */
    public DateUtil toTZ(String tz) {
        cal.setTimeZone(TimeZone.getTimeZone(tz));
        
        return this;
    }
    
    /**
     * Get the days passed from the specified date up to the date provided 
     * in the constructor
     *
     * @param date The starting date
     *
     * @return number of days within date used in constructor and the provided
     * date
     */
    public int getDaysSince(Date date) {
        long millisecs = date.getTime();
        Date d = cal.getTime();
        long time = d.getTime();
        long daysMillisecs = time - millisecs;
        int days = (int)((((daysMillisecs / 1000)/60)/60)/24);
        return days;
    }
    
    /**
     * Utility method wrapping Calendar.after method
     * Compares the date field parameter with the date provided with the constructor
     * answering the question: date from constructor is after the given param date ?
     *
     * @param date The date to be used for comparison
     *
     * @return true if date from constructor is after given param date
     */
    public boolean isAfter(Date date) {
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date);
        return cal.after(cal2);
    }
}





Convert time between timezone

   
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class Main {
  public static void main(String[] args) {
    Calendar localTime = Calendar.getInstance();
    localTime.set(Calendar.HOUR, 17);
    localTime.set(Calendar.MINUTE, 15);
    localTime.set(Calendar.SECOND, 20);
    int hour = localTime.get(Calendar.HOUR);
    int minute = localTime.get(Calendar.MINUTE);
    int second = localTime.get(Calendar.SECOND);
    System.out.printf("Local time  : %02d:%02d:%02d\n", hour, minute, second);
    Calendar germanyTime = new GregorianCalendar(TimeZone.getTimeZone("Germany"));
    germanyTime.setTimeInMillis(localTime.getTimeInMillis());
    hour = germanyTime.get(Calendar.HOUR);
    minute = germanyTime.get(Calendar.MINUTE);
    second = germanyTime.get(Calendar.SECOND);
    System.out.printf("Germany time: %02d:%02d:%02d\n", hour, minute, second);
  }
}





Create a Calendar object with the local time zone and set the UTC from japanCal

   
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class Main {
  public static void main(String[] argv) throws Exception {
    Calendar japanCal = new GregorianCalendar(TimeZone.getTimeZone("Japan"));
    japanCal.set(Calendar.HOUR_OF_DAY, 10); // 0..23
    japanCal.set(Calendar.MINUTE, 0);
    japanCal.set(Calendar.SECOND, 0);
    Calendar local = new GregorianCalendar();
    local.setTimeInMillis(japanCal.getTimeInMillis());
  }
}





Display Available Time Zones

   

import java.util.Arrays;
import java.util.TimeZone;
public class Main {
    public static void main(String[] args) {
        String[] allTimeZones = TimeZone.getAvailableIDs();
        
        Arrays.sort(allTimeZones);
        for (String timezone : allTimeZones) {
            System.out.println(timezone);
        }
    }
}
/*ACT
AET
AGT
ART
AST
Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara
Africa/Asmera
Africa/Bamako
Africa/Bangui
Africa/Banjul
Africa/Bissau
Africa/Blantyre
Africa/Brazzaville
Africa/Bujumbura
Africa/Cairo
Africa/Casablanca
Africa/Ceuta
Africa/Conakry
Africa/Dakar
Africa/Dar_es_Salaam
Africa/Djibouti
Africa/Douala
Africa/El_Aaiun
Africa/Freetown
Africa/Gaborone
Africa/Harare
Africa/Johannesburg
Africa/Kampala
Africa/Khartoum
Africa/Kigali
Africa/Kinshasa
Africa/Lagos
Africa/Libreville
Africa/Lome
Africa/Luanda
Africa/Lubumbashi
Africa/Lusaka
Africa/Malabo
Africa/Maputo
Africa/Maseru
Africa/Mbabane
Africa/Mogadishu
Africa/Monrovia
Africa/Nairobi
Africa/Ndjamena
Africa/Niamey
Africa/Nouakchott
Africa/Ouagadougou
Africa/Porto-Novo
Africa/Sao_Tome
Africa/Timbuktu
Africa/Tripoli
Africa/Tunis
Africa/Windhoek
America/Adak
America/Anchorage
America/Anguilla
America/Antigua
America/Araguaina
America/Argentina/Buenos_Aires
America/Argentina/Catamarca
America/Argentina/ComodRivadavia
America/Argentina/Cordoba
America/Argentina/Jujuy
America/Argentina/La_Rioja
America/Argentina/Mendoza
America/Argentina/Rio_Gallegos
America/Argentina/Salta
America/Argentina/San_Juan
America/Argentina/San_Luis
America/Argentina/Tucuman
America/Argentina/Ushuaia
America/Aruba
America/Asuncion
America/Atikokan
America/Atka
America/Bahia
America/Barbados
America/Belem
America/Belize
America/Blanc-Sablon
America/Boa_Vista
America/Bogota
America/Boise
America/Buenos_Aires
America/Cambridge_Bay
America/Campo_Grande
America/Cancun
America/Caracas
America/Catamarca
America/Cayenne
America/Cayman
America/Chicago
America/Chihuahua
America/Coral_Harbour
America/Cordoba
America/Costa_Rica
America/Cuiaba
America/Curacao
America/Danmarkshavn
America/Dawson
America/Dawson_Creek
America/Denver
America/Detroit
America/Dominica
America/Edmonton
America/Eirunepe
America/El_Salvador
America/Ensenada
America/Fort_Wayne
America/Fortaleza
America/Glace_Bay
America/Godthab
America/Goose_Bay
America/Grand_Turk
America/Grenada
America/Guadeloupe
America/Guatemala
America/Guayaquil
America/Guyana
America/Halifax
America/Havana
America/Hermosillo
America/Indiana/Indianapolis
America/Indiana/Knox
America/Indiana/Marengo
America/Indiana/Petersburg
America/Indiana/Tell_City
America/Indiana/Vevay
America/Indiana/Vincennes
America/Indiana/Winamac
America/Indianapolis
America/Inuvik
America/Iqaluit
America/Jamaica
America/Jujuy
America/Juneau
America/Kentucky/Louisville
America/Kentucky/Monticello
America/Knox_IN
America/La_Paz
America/Lima
America/Los_Angeles
America/Louisville
America/Maceio
America/Managua
America/Manaus
America/Marigot
America/Martinique
America/Mazatlan
America/Mendoza
America/Menominee
America/Merida
America/Mexico_City
America/Miquelon
America/Moncton
America/Monterrey
America/Montevideo
America/Montreal
America/Montserrat
America/Nassau
America/New_York
America/Nipigon
America/Nome
America/Noronha
America/North_Dakota/Center
America/North_Dakota/New_Salem
America/Panama
America/Pangnirtung
America/Paramaribo
America/Phoenix
America/Port-au-Prince
America/Port_of_Spain
America/Porto_Acre
America/Porto_Velho
America/Puerto_Rico
America/Rainy_River
America/Rankin_Inlet
America/Recife
America/Regina
America/Resolute
America/Rio_Branco
America/Rosario
America/Santarem
America/Santiago
America/Santo_Domingo
America/Sao_Paulo
America/Scoresbysund
America/Shiprock
America/St_Barthelemy
America/St_Johns
America/St_Kitts
America/St_Lucia
America/St_Thomas
America/St_Vincent
America/Swift_Current
America/Tegucigalpa
America/Thule
America/Thunder_Bay
America/Tijuana
America/Toronto
America/Tortola
America/Vancouver
America/Virgin
America/Whitehorse
America/Winnipeg
America/Yakutat
America/Yellowknife
Antarctica/Casey
Antarctica/Davis
Antarctica/DumontDUrville
Antarctica/Mawson
Antarctica/McMurdo
Antarctica/Palmer
Antarctica/Rothera
Antarctica/South_Pole
Antarctica/Syowa
Antarctica/Vostok
Arctic/Longyearbyen
Asia/Aden
Asia/Almaty
Asia/Amman
Asia/Anadyr
Asia/Aqtau
Asia/Aqtobe
Asia/Ashgabat
Asia/Ashkhabad
Asia/Baghdad
Asia/Bahrain
Asia/Baku
Asia/Bangkok
Asia/Beirut
Asia/Bishkek
Asia/Brunei
Asia/Calcutta
Asia/Choibalsan
Asia/Chongqing
Asia/Chungking
Asia/Colombo
Asia/Dacca
Asia/Damascus
Asia/Dhaka
Asia/Dili
Asia/Dubai
Asia/Dushanbe
Asia/Gaza
Asia/Harbin
Asia/Ho_Chi_Minh
Asia/Hong_Kong
Asia/Hovd
Asia/Irkutsk
Asia/Istanbul
Asia/Jakarta
Asia/Jayapura
Asia/Jerusalem
Asia/Kabul
Asia/Kamchatka
Asia/Karachi
Asia/Kashgar
Asia/Katmandu
Asia/Kolkata
Asia/Krasnoyarsk
Asia/Kuala_Lumpur
Asia/Kuching
Asia/Kuwait
Asia/Macao
Asia/Macau
Asia/Magadan
Asia/Makassar
Asia/Manila
Asia/Muscat
Asia/Nicosia
Asia/Novosibirsk
Asia/Omsk
Asia/Oral
Asia/Phnom_Penh
Asia/Pontianak
Asia/Pyongyang
Asia/Qatar
Asia/Qyzylorda
Asia/Rangoon
Asia/Riyadh
Asia/Riyadh87
Asia/Riyadh88
Asia/Riyadh89
Asia/Saigon
Asia/Sakhalin
Asia/Samarkand
Asia/Seoul
Asia/Shanghai
Asia/Singapore
Asia/Taipei
Asia/Tashkent
Asia/Tbilisi
Asia/Tehran
Asia/Tel_Aviv
Asia/Thimbu
Asia/Thimphu
Asia/Tokyo
Asia/Ujung_Pandang
Asia/Ulaanbaatar
Asia/Ulan_Bator
Asia/Urumqi
Asia/Vientiane
Asia/Vladivostok
Asia/Yakutsk
Asia/Yekaterinburg
Asia/Yerevan
Atlantic/Azores
Atlantic/Bermuda
Atlantic/Canary
Atlantic/Cape_Verde
Atlantic/Faeroe
Atlantic/Faroe
Atlantic/Jan_Mayen
Atlantic/Madeira
Atlantic/Reykjavik
Atlantic/South_Georgia
Atlantic/St_Helena
Atlantic/Stanley
Australia/ACT
Australia/Adelaide
Australia/Brisbane
Australia/Broken_Hill
Australia/Canberra
Australia/Currie
Australia/Darwin
Australia/Eucla
Australia/Hobart
Australia/LHI
Australia/Lindeman
Australia/Lord_Howe
Australia/Melbourne
Australia/NSW
Australia/North
Australia/Perth
Australia/Queensland
Australia/South
Australia/Sydney
Australia/Tasmania
Australia/Victoria
Australia/West
Australia/Yancowinna
BET
BST
Brazil/Acre
Brazil/DeNoronha
Brazil/East
Brazil/West
CAT
CET
CNT
CST
CST6CDT
CTT
Canada/Atlantic
Canada/Central
Canada/East-Saskatchewan
Canada/Eastern
Canada/Mountain
Canada/Newfoundland
Canada/Pacific
Canada/Saskatchewan
Canada/Yukon
Chile/Continental
Chile/EasterIsland
Cuba
EAT
ECT
EET
EST
EST5EDT
Egypt
Eire
Etc/GMT
Etc/GMT+0
Etc/GMT+1
Etc/GMT+10
Etc/GMT+11
Etc/GMT+12
Etc/GMT+2
Etc/GMT+3
Etc/GMT+4
Etc/GMT+5
Etc/GMT+6
Etc/GMT+7
Etc/GMT+8
Etc/GMT+9
Etc/GMT-0
Etc/GMT-1
Etc/GMT-10
Etc/GMT-11
Etc/GMT-12
Etc/GMT-13
Etc/GMT-14
Etc/GMT-2
Etc/GMT-3
Etc/GMT-4
Etc/GMT-5
Etc/GMT-6
Etc/GMT-7
Etc/GMT-8
Etc/GMT-9
Etc/GMT0
Etc/Greenwich
Etc/UCT
Etc/UTC
Etc/Universal
Etc/Zulu
Europe/Amsterdam
Europe/Andorra
Europe/Athens
Europe/Belfast
Europe/Belgrade
Europe/Berlin
Europe/Bratislava
Europe/Brussels
Europe/Bucharest
Europe/Budapest
Europe/Chisinau
Europe/Copenhagen
Europe/Dublin
Europe/Gibraltar
Europe/Guernsey
Europe/Helsinki
Europe/Isle_of_Man
Europe/Istanbul
Europe/Jersey
Europe/Kaliningrad
Europe/Kiev
Europe/Lisbon
Europe/Ljubljana
Europe/London
Europe/Luxembourg
Europe/Madrid
Europe/Malta
Europe/Mariehamn
Europe/Minsk
Europe/Monaco
Europe/Moscow
Europe/Nicosia
Europe/Oslo
Europe/Paris
Europe/Podgorica
Europe/Prague
Europe/Riga
Europe/Rome
Europe/Samara
Europe/San_Marino
Europe/Sarajevo
Europe/Simferopol
Europe/Skopje
Europe/Sofia
Europe/Stockholm
Europe/Tallinn
Europe/Tirane
Europe/Tiraspol
Europe/Uzhgorod
Europe/Vaduz
Europe/Vatican
Europe/Vienna
Europe/Vilnius
Europe/Volgograd
Europe/Warsaw
Europe/Zagreb
Europe/Zaporozhye
Europe/Zurich
GB
GB-Eire
GMT
GMT0
Greenwich
HST
Hongkong
IET
IST
Iceland
Indian/Antananarivo
Indian/Chagos
Indian/Christmas
Indian/Cocos
Indian/Comoro
Indian/Kerguelen
Indian/Mahe
Indian/Maldives
Indian/Mauritius
Indian/Mayotte
Indian/Reunion
Iran
Israel
JST
Jamaica
Japan
Kwajalein
Libya
MET
MIT
MST
MST7MDT
Mexico/BajaNorte
Mexico/BajaSur
Mexico/General
Mideast/Riyadh87
Mideast/Riyadh88
Mideast/Riyadh89
NET
NST
NZ
NZ-CHAT
Navajo
PLT
PNT
PRC
PRT
PST
PST8PDT
Pacific/Apia
Pacific/Auckland
Pacific/Chatham
Pacific/Easter
Pacific/Efate
Pacific/Enderbury
Pacific/Fakaofo
Pacific/Fiji
Pacific/Funafuti
Pacific/Galapagos
Pacific/Gambier
Pacific/Guadalcanal
Pacific/Guam
Pacific/Honolulu
Pacific/Johnston
Pacific/Kiritimati
Pacific/Kosrae
Pacific/Kwajalein
Pacific/Majuro
Pacific/Marquesas
Pacific/Midway
Pacific/Nauru
Pacific/Niue
Pacific/Norfolk
Pacific/Noumea
Pacific/Pago_Pago
Pacific/Palau
Pacific/Pitcairn
Pacific/Ponape
Pacific/Port_Moresby
Pacific/Rarotonga
Pacific/Saipan
Pacific/Samoa
Pacific/Tahiti
Pacific/Tarawa
Pacific/Tongatapu
Pacific/Truk
Pacific/Wake
Pacific/Wallis
Pacific/Yap
Poland
Portugal
ROK
SST
Singapore
SystemV/AST4
SystemV/AST4ADT
SystemV/CST6
SystemV/CST6CDT
SystemV/EST5
SystemV/EST5EDT
SystemV/HST10
SystemV/MST7
SystemV/MST7MDT
SystemV/PST8
SystemV/PST8PDT
SystemV/YST9
SystemV/YST9YDT
Turkey
UCT
US/Alaska
US/Aleutian
US/Arizona
US/Central
US/East-Indiana
US/Eastern
US/Hawaii
US/Indiana-Starke
US/Michigan
US/Mountain
US/Pacific
US/Pacific-New
US/Samoa
UTC
Universal
VST
W-SU
WET
Zulu
*/





Format TimeZone in z (General time zone) format like EST.

   
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
  public static void main(String[] args) {
    Date date = new Date();

    SimpleDateFormat sdf = new SimpleDateFormat("zzz");
    System.out.println("TimeZone in z format : " + sdf.format(date));
  }
}
//TimeZone in z format : PST





Format TimeZone in Z (RFC 822) format like -8000.

   
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
  public static void main(String[] args) {
    Date date = new Date();
    
    SimpleDateFormat sdf = new SimpleDateFormat("Z");
    System.out.println("TimeZone in Z format : " + sdf.format(date));
  }
}
//TimeZone in Z format : -0800





Format TimeZone in zzzz format Eastern Standard Time.

   
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
  public static void main(String[] args) {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("zzzz");
    System.out.println("TimeZone in zzzz format : " + sdf.format(date));
  }
}
//TimeZone in zzzz format : Pacific Standard Time





Get all available timezones

   
 
import java.util.TimeZone;
public class Main {
  public static void main(String[] args) {
    String[] availableTimezones = TimeZone.getAvailableIDs();
    for (String timezone : availableTimezones) {
      System.out.println("Timezone ID = " + timezone);
    }
  }
}





Get current TimeZone using Java Calendar

   
import java.util.Calendar;
import java.util.TimeZone;
public class Main {
  public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    TimeZone timeZone = now.getTimeZone();
    System.out.println("Current TimeZone is : " + timeZone.getDisplayName());
  }
}





Get the time in the local time zone

   
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class Main {
  public static void main(String[] argv) throws Exception {
    Calendar japanCal = new GregorianCalendar(TimeZone.getTimeZone("Japan"));
    japanCal.set(Calendar.HOUR_OF_DAY, 10); // 0..23
    japanCal.set(Calendar.MINUTE, 0);
    japanCal.set(Calendar.SECOND, 0);
    Calendar local = new GregorianCalendar();
    local.setTimeInMillis(japanCal.getTimeInMillis());
    int hour = local.get(Calendar.HOUR); // 5
    int minutes = local.get(Calendar.MINUTE); // 0
    int seconds = local.get(Calendar.SECOND); // 0
    boolean am = local.get(Calendar.AM_PM) == Calendar.AM; // false
  }
}





Getting the Current Time in Another Time Zone

   
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Get the current time in Hong Kong
    Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("Hongkong"));
    int hour12 = cal.get(Calendar.HOUR); // 0..11
    int minutes = cal.get(Calendar.MINUTE); // 0..59
    int seconds = cal.get(Calendar.SECOND); // 0..59
    boolean am = cal.get(Calendar.AM_PM) == Calendar.AM;
    // Get the current hour-of-day at GMT
    cal.setTimeZone(TimeZone.getTimeZone("GMT"));
    int hour24 = cal.get(Calendar.HOUR_OF_DAY); // 0..23
    // Get the current local hour-of-day
    cal.setTimeZone(TimeZone.getDefault());
    hour24 = cal.get(Calendar.HOUR_OF_DAY); // 0..23
  }
}





Timezone conversion routines

  
/*
   Copyright (C) 2002 MySQL AB
   
      This program is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published by
      the Free Software Foundation; either version 2 of the License, or
      (at your option) any later version.
   
      This program is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      GNU General Public License for more details.
   
      You should have received a copy of the GNU General Public License
      along with this program; if not, write to the Free Software
      Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
      
 */

import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.TimeZone;
/**
 * Timezone conversion routines
 * 
 * @author Mark Matthews
 */
public class TimeUtil
{
    //~ Instance/static variables .............................................
    static TimeZone GMT_TIMEZONE = TimeZone.getTimeZone("GMT");
    static final HashMap TIMEZONE_MAPPINGS;
    //~ Initializers ..........................................................
    static {
        TIMEZONE_MAPPINGS = new HashMap(175);
        //
        // Windows Mappings
        //
        TIMEZONE_MAPPINGS.put("Romance", "Europe/Paris");
        TIMEZONE_MAPPINGS.put("Romance Standard Time", "Europe/Paris");
        TIMEZONE_MAPPINGS.put("Warsaw", "Europe/Warsaw");
        TIMEZONE_MAPPINGS.put("Central Europe", "Europe/Prague");
        TIMEZONE_MAPPINGS.put("Central Europe Standard Time", "Europe/Prague");
        TIMEZONE_MAPPINGS.put("Prague Bratislava", "Europe/Prague");
        TIMEZONE_MAPPINGS.put("W. Central Africa Standard Time", 
                              "Africa/Luanda");
        TIMEZONE_MAPPINGS.put("FLE", "Europe/Helsinki");
        TIMEZONE_MAPPINGS.put("FLE Standard Time", "Europe/Helsinki");
        TIMEZONE_MAPPINGS.put("GFT", "Europe/Athens");
        TIMEZONE_MAPPINGS.put("GFT Standard Time", "Europe/Athens");
        TIMEZONE_MAPPINGS.put("GTB", "Europe/Athens");
        TIMEZONE_MAPPINGS.put("GTB Standard Time", "Europe/Athens");
        TIMEZONE_MAPPINGS.put("Israel", "Asia/Jerusalem");
        TIMEZONE_MAPPINGS.put("Israel Standard Time", "Asia/Jerusalem");
        TIMEZONE_MAPPINGS.put("Arab", "Asia/Riyadh");
        TIMEZONE_MAPPINGS.put("Arab Standard Time", "Asia/Riyadh");
        TIMEZONE_MAPPINGS.put("Arabic Standard Time", "Asia/Baghdad");
        TIMEZONE_MAPPINGS.put("E. Africa", "Africa/Nairobi");
        TIMEZONE_MAPPINGS.put("E. Africa Standard Time", "Africa/Nairobi");
        TIMEZONE_MAPPINGS.put("Saudi Arabia", "Asia/Riyadh");
        TIMEZONE_MAPPINGS.put("Saudi Arabia Standard Time", "Asia/Riyadh");
        TIMEZONE_MAPPINGS.put("Iran", "Asia/Tehran");
        TIMEZONE_MAPPINGS.put("Iran Standard Time", "Asia/Tehran");
        TIMEZONE_MAPPINGS.put("Afghanistan", "Asia/Kabul");
        TIMEZONE_MAPPINGS.put("Afghanistan Standard Time", "Asia/Kabul");
        TIMEZONE_MAPPINGS.put("India", "Asia/Calcutta");
        TIMEZONE_MAPPINGS.put("India Standard Time", "Asia/Calcutta");
        TIMEZONE_MAPPINGS.put("Myanmar Standard Time", "Asia/Rangoon");
        TIMEZONE_MAPPINGS.put("Nepal Standard Time", "Asia/Katmandu");
        TIMEZONE_MAPPINGS.put("Sri Lanka", "Asia/Colombo");
        TIMEZONE_MAPPINGS.put("Sri Lanka Standard Time", "Asia/Colombo");
        TIMEZONE_MAPPINGS.put("Beijing", "Asia/Shanghai");
        TIMEZONE_MAPPINGS.put("China", "Asia/Shanghai");
        TIMEZONE_MAPPINGS.put("China Standard Time", "Asia/Shanghai");
        TIMEZONE_MAPPINGS.put("AUS Central", "Australia/Darwin");
        TIMEZONE_MAPPINGS.put("AUS Central Standard Time", "Australia/Darwin");
        TIMEZONE_MAPPINGS.put("Cen. Australia", "Australia/Adelaide");
        TIMEZONE_MAPPINGS.put("Cen. Australia Standard Time", 
                              "Australia/Adelaide");
        TIMEZONE_MAPPINGS.put("Vladivostok", "Asia/Vladivostok");
        TIMEZONE_MAPPINGS.put("Vladivostok Standard Time", "Asia/Vladivostok");
        TIMEZONE_MAPPINGS.put("West Pacific", "Pacific/Guam");
        TIMEZONE_MAPPINGS.put("West Pacific Standard Time", "Pacific/Guam");
        TIMEZONE_MAPPINGS.put("E. South America", "America/Sao_Paulo");
        TIMEZONE_MAPPINGS.put("E. South America Standard Time", 
                              "America/Sao_Paulo");
        TIMEZONE_MAPPINGS.put("Greenland Standard Time", "America/Godthab");
        TIMEZONE_MAPPINGS.put("Newfoundland", "America/St_Johns");
        TIMEZONE_MAPPINGS.put("Newfoundland Standard Time", "America/St_Johns");
        TIMEZONE_MAPPINGS.put("Pacific SA", "America/Caracas");
        TIMEZONE_MAPPINGS.put("Pacific SA Standard Time", "America/Caracas");
        TIMEZONE_MAPPINGS.put("SA Western", "America/Caracas");
        TIMEZONE_MAPPINGS.put("SA Western Standard Time", "America/Caracas");
        TIMEZONE_MAPPINGS.put("SA Pacific", "America/Bogota");
        TIMEZONE_MAPPINGS.put("SA Pacific Standard Time", "America/Bogota");
        TIMEZONE_MAPPINGS.put("US Eastern", "America/Indianapolis");
        TIMEZONE_MAPPINGS.put("US Eastern Standard Time", 
                              "America/Indianapolis");
        TIMEZONE_MAPPINGS.put("Central America Standard Time", 
                              "America/Regina");
        TIMEZONE_MAPPINGS.put("Mexico", "America/Mexico_City");
        TIMEZONE_MAPPINGS.put("Mexico Standard Time", "America/Mexico_City");
        TIMEZONE_MAPPINGS.put("Canada Central", "America/Regina");
        TIMEZONE_MAPPINGS.put("Canada Central Standard Time", "America/Regina");
        TIMEZONE_MAPPINGS.put("US Mountain", "America/Phoenix");
        TIMEZONE_MAPPINGS.put("US Mountain Standard Time", "America/Phoenix");
        TIMEZONE_MAPPINGS.put("GMT", "Europe/London");
        TIMEZONE_MAPPINGS.put("GMT Standard Time", "Europe/London");
        TIMEZONE_MAPPINGS.put("Ekaterinburg", "Asia/Yekaterinburg");
        TIMEZONE_MAPPINGS.put("Ekaterinburg Standard Time", 
                              "Asia/Yekaterinburg");
        TIMEZONE_MAPPINGS.put("West Asia", "Asia/Karachi");
        TIMEZONE_MAPPINGS.put("West Asia Standard Time", "Asia/Karachi");
        TIMEZONE_MAPPINGS.put("Central Asia", "Asia/Dhaka");
        TIMEZONE_MAPPINGS.put("Central Asia Standard Time", "Asia/Dhaka");
        TIMEZONE_MAPPINGS.put("N. Central Asia Standard Time", 
                              "Asia/Novosibirsk");
        TIMEZONE_MAPPINGS.put("Bangkok", "Asia/Bangkok");
        TIMEZONE_MAPPINGS.put("Bangkok Standard Time", "Asia/Bangkok");
        TIMEZONE_MAPPINGS.put("North Asia Standard Time", "Asia/Krasnoyarsk");
        TIMEZONE_MAPPINGS.put("SE Asia", "Asia/Bangkok");
        TIMEZONE_MAPPINGS.put("SE Asia Standard Time", "Asia/Bangkok");
        TIMEZONE_MAPPINGS.put("North Asia East Standard Time", 
                              "Asia/Ulaanbaatar");
        TIMEZONE_MAPPINGS.put("Singapore", "Asia/Singapore");
        TIMEZONE_MAPPINGS.put("Singapore Standard Time", "Asia/Singapore");
        TIMEZONE_MAPPINGS.put("Taipei", "Asia/Taipei");
        TIMEZONE_MAPPINGS.put("Taipei Standard Time", "Asia/Taipei");
        TIMEZONE_MAPPINGS.put("W. Australia", "Australia/Perth");
        TIMEZONE_MAPPINGS.put("W. Australia Standard Time", "Australia/Perth");
        TIMEZONE_MAPPINGS.put("Korea", "Asia/Seoul");
        TIMEZONE_MAPPINGS.put("Korea Standard Time", "Asia/Seoul");
        TIMEZONE_MAPPINGS.put("Tokyo", "Asia/Tokyo");
        TIMEZONE_MAPPINGS.put("Tokyo Standard Time", "Asia/Tokyo");
        TIMEZONE_MAPPINGS.put("Yakutsk", "Asia/Yakutsk");
        TIMEZONE_MAPPINGS.put("Yakutsk Standard Time", "Asia/Yakutsk");
        TIMEZONE_MAPPINGS.put("Central European", "Europe/Belgrade");
        TIMEZONE_MAPPINGS.put("Central European Standard Time", 
                              "Europe/Belgrade");
        TIMEZONE_MAPPINGS.put("W. Europe", "Europe/Berlin");
        TIMEZONE_MAPPINGS.put("W. Europe Standard Time", "Europe/Berlin");
        TIMEZONE_MAPPINGS.put("Tasmania", "Australia/Hobart");
        TIMEZONE_MAPPINGS.put("Tasmania Standard Time", "Australia/Hobart");
        TIMEZONE_MAPPINGS.put("AUS Eastern", "Australia/Sydney");
        TIMEZONE_MAPPINGS.put("AUS Eastern Standard Time", "Australia/Sydney");
        TIMEZONE_MAPPINGS.put("E. Australia", "Australia/Brisbane");
        TIMEZONE_MAPPINGS.put("E. Australia Standard Time", 
                              "Australia/Brisbane");
        TIMEZONE_MAPPINGS.put("Sydney Standard Time", "Australia/Sydney");
        TIMEZONE_MAPPINGS.put("Central Pacific", "Pacific/Guadalcanal");
        TIMEZONE_MAPPINGS.put("Central Pacific Standard Time", 
                              "Pacific/Guadalcanal");
        TIMEZONE_MAPPINGS.put("Dateline", "Pacific/Majuro");
        TIMEZONE_MAPPINGS.put("Dateline Standard Time", "Pacific/Majuro");
        TIMEZONE_MAPPINGS.put("Fiji", "Pacific/Fiji");
        TIMEZONE_MAPPINGS.put("Fiji Standard Time", "Pacific/Fiji");
        TIMEZONE_MAPPINGS.put("Samoa", "Pacific/Apia");
        TIMEZONE_MAPPINGS.put("Samoa Standard Time", "Pacific/Apia");
        TIMEZONE_MAPPINGS.put("Hawaiian", "Pacific/Honolulu");
        TIMEZONE_MAPPINGS.put("Hawaiian Standard Time", "Pacific/Honolulu");
        TIMEZONE_MAPPINGS.put("Alaskan", "America/Anchorage");
        TIMEZONE_MAPPINGS.put("Alaskan Standard Time", "America/Anchorage");
        TIMEZONE_MAPPINGS.put("Pacific", "America/Los_Angeles");
        TIMEZONE_MAPPINGS.put("Pacific Standard Time", "America/Los_Angeles");
        TIMEZONE_MAPPINGS.put("Mexico Standard Time 2", "America/Chihuahua");
        TIMEZONE_MAPPINGS.put("Mountain", "America/Denver");
        TIMEZONE_MAPPINGS.put("Mountain Standard Time", "America/Denver");
        TIMEZONE_MAPPINGS.put("Central", "America/Chicago");
        TIMEZONE_MAPPINGS.put("Central Standard Time", "America/Chicago");
        TIMEZONE_MAPPINGS.put("Eastern", "America/New_York");
        TIMEZONE_MAPPINGS.put("Eastern Standard Time", "America/New_York");
        TIMEZONE_MAPPINGS.put("E. Europe", "Europe/Bucharest");
        TIMEZONE_MAPPINGS.put("E. Europe Standard Time", "Europe/Bucharest");
        TIMEZONE_MAPPINGS.put("Egypt", "Africa/Cairo");
        TIMEZONE_MAPPINGS.put("Egypt Standard Time", "Africa/Cairo");
        TIMEZONE_MAPPINGS.put("South Africa", "Africa/Harare");
        TIMEZONE_MAPPINGS.put("South Africa Standard Time", "Africa/Harare");
        TIMEZONE_MAPPINGS.put("Atlantic", "America/Halifax");
        TIMEZONE_MAPPINGS.put("Atlantic Standard Time", "America/Halifax");
        TIMEZONE_MAPPINGS.put("SA Eastern", "America/Buenos_Aires");
        TIMEZONE_MAPPINGS.put("SA Eastern Standard Time", 
                              "America/Buenos_Aires");
        TIMEZONE_MAPPINGS.put("Mid-Atlantic", "Atlantic/South_Georgia");
        TIMEZONE_MAPPINGS.put("Mid-Atlantic Standard Time", 
                              "Atlantic/South_Georgia");
        TIMEZONE_MAPPINGS.put("Azores", "Atlantic/Azores");
        TIMEZONE_MAPPINGS.put("Azores Standard Time", "Atlantic/Azores");
        TIMEZONE_MAPPINGS.put("Cape Verde Standard Time", 
                              "Atlantic/Cape_Verde");
        TIMEZONE_MAPPINGS.put("Russian", "Europe/Moscow");
        TIMEZONE_MAPPINGS.put("Russian Standard Time", "Europe/Moscow");
        TIMEZONE_MAPPINGS.put("New Zealand", "Pacific/Auckland");
        TIMEZONE_MAPPINGS.put("New Zealand Standard Time", "Pacific/Auckland");
        TIMEZONE_MAPPINGS.put("Tonga Standard Time", "Pacific/Tongatapu");
        TIMEZONE_MAPPINGS.put("Arabian", "Asia/Muscat");
        TIMEZONE_MAPPINGS.put("Arabian Standard Time", "Asia/Muscat");
        TIMEZONE_MAPPINGS.put("Caucasus", "Asia/Tbilisi");
        TIMEZONE_MAPPINGS.put("Caucasus Standard Time", "Asia/Tbilisi");
        TIMEZONE_MAPPINGS.put("GMT Standard Time", "GMT");
        TIMEZONE_MAPPINGS.put("Greenwich", "GMT");
        TIMEZONE_MAPPINGS.put("Greenwich Standard Time", "GMT");
    }
    //~ Methods ...............................................................
    public static String getCanoncialTimezone(String timezoneStr)
    {
        if (timezoneStr == null) {
            return null;
        }
        timezoneStr = timezoneStr.trim();
        // Fix windows Daylight/Standard shift JDK doesn"t map these (doh)
        String timezoneStrUC = timezoneStr.toUpperCase();
        int daylightIndex = timezoneStrUC.indexOf("DAYLIGHT");
        if (daylightIndex != -1) {
            StringBuffer timezoneBuf = new StringBuffer();
            timezoneBuf.append(timezoneStr.substring(0, daylightIndex));
            timezoneBuf.append("Standard");
            timezoneBuf.append(timezoneStr.substring(
                                       daylightIndex + "DAYLIGHT".length(), 
                                       timezoneStr.length()));
            timezoneStr = timezoneBuf.toString();
        }
        return (String)TIMEZONE_MAPPINGS.get(timezoneStr);
    }
    public static Timestamp changeTimezone(Timestamp tstamp, TimeZone fromTz, 
                                           TimeZone toTz)
    {
        /*
           // Convert the timestamp to the GMT timezone
           Calendar fromCal = Calendar.getInstance(fromTz);
           fromCal.setTime(tstamp);
           int fromOffset =
                   fromCal.get(Calendar.ZONE_OFFSET)
                           + fromCal.get(Calendar.DST_OFFSET);
           Calendar toCal = Calendar.getInstance(toTz);
           toCal.setTime(tstamp);
           int toOffset =
                   toCal.get(Calendar.ZONE_OFFSET) + toCal.get(Calendar.DST_OFFSET);
           int offsetDiff = toOffset - fromOffset;
           long toTime = toCal.getTime().getTime();
           toTime += offsetDiff;
           Timestamp changedTimestamp = new Timestamp(toTime);
           return changedTimestamp;
         */
        return tstamp;
    }
    public static Time changeTimezone(Time t, TimeZone fromTz, TimeZone toTz)
    {
        /*
           // Convert the timestamp to the GMT timezone
           Calendar fromCal = Calendar.getInstance(fromTz);
           fromCal.setTime(t);
           int fromOffset =
                   fromCal.get(Calendar.ZONE_OFFSET)
                           + fromCal.get(Calendar.DST_OFFSET);
           Calendar toCal = Calendar.getInstance(toTz);
           toCal.setTime(t);
           int toOffset =
                   toCal.get(Calendar.ZONE_OFFSET) + toCal.get(Calendar.DST_OFFSET);
           int offsetDiff = toOffset - fromOffset;
           long toTime = toCal.getTime().getTime();
           toTime += offsetDiff;
           Time changedTime = new Time(toTime);
           return changedTime;
         */
        return t;
    }
}





TimeZone.getTimeZone("America/New_York")

   
import java.util.Calendar;
import java.util.TimeZone;
public class Main {
  public static void main(String[] args) {
    Calendar calNewYork = Calendar.getInstance();
    calNewYork.setTimeZone(TimeZone.getTimeZone("America/New_York"));
    System.out.println("Time in New York: " + calNewYork.get(Calendar.HOUR_OF_DAY) + ":"
        + calNewYork.get(Calendar.MINUTE));
  }
}
//Time in New York: 11:51





TimeZone.getTimeZone("Asia/Tokyo")

   
import java.util.Calendar;
import java.util.TimeZone;
public class Main {
  public static void main(String[] args) {
    Calendar calTokyo = Calendar.getInstance();
    calTokyo.setTimeZone(TimeZone.getTimeZone("Asia/Tokyo"));
    System.out.println("Time in Tokyo: " + calTokyo.get(Calendar.HOUR_OF_DAY) + ":"
        + calTokyo.get(Calendar.MINUTE));
  }
}
//Time in Tokyo: 1:51





TimeZone.getTimeZone("Europe/Paris")

   
import java.util.Calendar;
import java.util.TimeZone;
public class Main {
  public static void main(String[] args) {
    Calendar calParis = Calendar.getInstance();
    calParis.setTimeZone(TimeZone.getTimeZone("Europe/Paris"));
    System.out.println("Time in Paris: " + calParis.get(Calendar.HOUR_OF_DAY) + ":"
        + calParis.get(Calendar.MINUTE));
  }
}
//Time in Paris: 17:51





Using the Calendar Class to Display Current Time in Different Time Zones

   
import java.util.Calendar;
import java.util.TimeZone;
public class Main {
  public static void main(String[] args) {
    Calendar calNewYork = Calendar.getInstance();
    calNewYork.setTimeZone(TimeZone.getTimeZone("America/New_York"));
    System.out.println("Time in New York: " + calNewYork.get(Calendar.HOUR_OF_DAY) + ":"
        + calNewYork.get(Calendar.MINUTE));
  }
}
//Time in New York: 11:51