How to adjust the GMT offset during Daylight Saving Time?

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

public class CalendarTest { 
    private TimeZone timeZone; 
    public CalendarTest(){ 
    	timeZone = TimeZone.getDefault(); 
    } 

    TimeZone getDefaultTimeZone(){ 
        return timeZone; 
    } 

    public boolean checkIfNowAtDST(){ 
    	return checkIfNowAtDST(timeZone.getDisplayName()); 
    } 

    public boolean checkIfNowAtDST(String iTimezoneName){ 

        /************************************* 
         * US. 2007 energy policy 
         * DST starts:      at 2:00am in standard time 
         *                  on the second Sunday in March 
         * DST ends:        at 2:00am in daylight time 
         *                  on the first Sunday in November 
         * *********************************** 
         */ 

    	boolean isDST = false; 
    	TimeZone iTimezone = TimeZone.getTimeZone(iTimezoneName); 
             SimpleTimeZone stz = new SimpleTimeZone(iTimezone.getRawOffset(), 
        		iTimezoneName, 
                	Calendar.MARCH, 8, -Calendar.SUNDAY, 
                	7200000, 
                	Calendar.NOVEMBER, 1, -Calendar.SUNDAY, 
                	7200000, 
                	3600000); 

             if(stz.inDaylightTime(new Date())){ 
              	isDST = true; 
             } 

             return isDST; 
    } 

    public long getDateTimeGMTOffset(long iDate, String iTimezone) { 
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(iTimezone)); 
        return iDate - calendar.get(Calendar.ZONE_OFFSET) - calendar.get(Calendar.DST_OFFSET); 
    } 

    public String toString() { 
    	int offset = getDefaultTimeZone().getRawOffset() / 1000 / 60 / 60; 
    	return TimeZone.getDefault().getDisplayName(false, TimeZone.SHORT) + " (UTC" + offset + ")"; 
    } 

    public static void main(String[] args) { 
    	CalendarTest test = new CalendarTest(); 
    	System.out.println("Default time zone is: " + test.toString()); 
    	System.out.println("Is now at Daylight saving time?" + test.checkIfNowAtDST() ? "Yes" : "No"); 
    	//test the customized timezone 
    	long offset = 0L; 
    	String iTimezoneName = "EST"; 
    	boolean isNowatDST = test.checkIfNowAtDST(iTimezoneName); 

    	//adjust the GMT offset 
    	//if now time is during DST, then offset would be 14400000, otherwise 18000000. 
    	TimeZone iTimezone = TimeZone.getTimeZone(iTimezoneName); 
             Calendar iCalendar = Calendar.getInstance(TimeZone.getTimeZone(iTimezoneName)); 
             if(isNowatDST){ 
                offset = -iCalendar.get(Calendar.ZONE_OFFSET) - iCalendar.get(Calendar.DST_OFFSET); 
            }else{ 
                offset = -iCalendar.get(Calendar.ZONE_OFFSET); 
            } 
            System.out.println("time zone offset: "+offset); 
     }  
}

How to convert Database GMT TimeZone when there is different JVM TimeZone?

public class GMTWriter { 
    public Calendar getCalendar(Date date) { 
        if (date == null) 
    	   return null; 
        Calendar calendar = Calendar.getInstance(); 
        calendar.setTimeZone(TimeZone.getTimeZone("GMT")); 
        calendar.setTime(date); 
        return calendar; 
    } 
} 

public class GMTReader { 
    private static final Calendar calendar; 
    // Create a dummy Calendar object to store the GMT timezone. 
    static { 
        calendar = Calendar.getInstance(); 
        calendar.setTimeZone(TimeZone.getTimeZone("GMT")); 
    } 

    public Calendar getCalendar() { 
         return calendar; 
    } 

} 

//in the preparedstatement, you assume DB store is GMT timestamp, 
//then you want to retrieve the timestamp is as the same GMT 
//no matter what your JVM time zone is EST or PST. 

long dueDate = resultSet.getTimestamp(duedate, GMTReader.getCalendar());

[UnitTest]

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

public class CalendarTest2 {
	public static void main(String[] args) {
		String iTimezoneName = "PST";
		TimeZone iTimezone = TimeZone.getTimeZone(iTimezoneName);
		SimpleTimeZone stz = new SimpleTimeZone(iTimezone.getRawOffset(),
		      iTimezoneName,
		      Calendar.MARCH, 8, -Calendar.SUNDAY,
		      2 * 60 * 60 * 1000,
		      Calendar.NOVEMBER, 1, -Calendar.SUNDAY,
		      2 * 60 * 60 * 1000, 60 * 60 * 1000);

		boolean isDST = false;
		GregorianCalendar gc01 = new GregorianCalendar(2007, Calendar.MARCH, 11);
		Date date041107 = gc01.getTime();
		if(stz.inDaylightTime(date041107)){
		    isDST = true;
                          }else{
			isDST = false;
		}
		System.out.println("Test Date: " + date041107 + " is " + (isDST ? " at" : "NOT at") + " DST.");

		gc01 = new GregorianCalendar(2007, Calendar.MARCH, 12);
		Date date041207 = gc01.getTime();
		if(stz.inDaylightTime(date041207)){
		    isDST = true;
                         }else{
			isDST = false;
		}
		System.out.println("Test Date: " + date041207 + " is " + (isDST ? " at" : "NOT at") + " DST.");

		GregorianCalendar gc02 = new GregorianCalendar(2007, Calendar.NOVEMBER, 04);
		Date date110407 = gc02.getTime();
		if(stz.inDaylightTime(date110407)){
		    isDST = true;
                          }else{
			isDST = false;
		}
		System.out.println("Test Date: " + date110407 + " is " + (isDST ? " at" : "NOT at") + " DST.");

		gc02 = new GregorianCalendar(2007, Calendar.NOVEMBER, 05);
		Date date110507 = gc02.getTime();
		if(stz.inDaylightTime(date110507)){
		    isDST = true;
                          }else{
			isDST = false;
		}
	             System.out.println("Test Date: " + date110507 + " is " + (isDST ? " at" : "NOT at") + " DST.");
	}
}

The result looks like:
C:\temp>java -cp . CalendarTest2
Test Date: Sun Mar 11 00:00:00 PST 2007 is NOT at DST.
Test Date: Mon Mar 12 00:00:00 PDT 2007 is at DST.
Test Date: Sun Nov 04 00:00:00 PDT 2007 is at DST.
Test Date: Mon Nov 05 00:00:00 PST 2007 is NOT at DST.

JDK version issue:
If you are concerned about application failures that may result from these DST changes, you should update your Java Runtime Environment. The following Java platform versions have correct time rules to handle the DST changes that will affect U.S. time zones in 2007. You can download any of the following Java platform versions to resolve this DST issue:

JDK 6 Project (beta)
J2SE 5.0 Update 6 or later
J2SE 1.4.2_11 or later

Ref:
Sun
What’s your time zone?
Making Sense of Java’s Dates

update 04-05-2009:
Convent Java to GMT from IeriWinner_30

update 06-19-2009:

	/**
	 * to convert UTC date to specific time zone
	 * @param iDate UTC date at scheduler
	 * @param localTimeZoneID shop time zone
	 * @return retDate is offset from UTC but the time zone still UTC. Don't depend on this date's time zone!
	 */
	public java.util.Date UTCtoLocalTimezone(Date iDate, String localTimeZoneID){
		log.debug("localTimeZoneName: "+localTimeZoneID);
		log.debug("Original Date: " + iDate);
		Date retDate = null;
		TimeZone tz = TimeZone.getTimeZone(localTimeZoneID);
		
		//Daylight saving time in USA
		SimpleTimeZone stz = new SimpleTimeZone(tz.getRawOffset(),
				localTimeZoneID,  Calendar.MARCH, 8, -Calendar.SUNDAY, 2 * 60 * 60 * 1000,
			    Calendar.NOVEMBER, 1, -Calendar.SUNDAY, 2 * 60 * 60 * 1000, 60 * 60 * 1000);
		if (iDate != null) {			
			retDate = new Date(iDate.getTime() + tz.getRawOffset());
			//check if DST
			if (stz.inDaylightTime(retDate)){	
				log.debug("isDST=true");				
				retDate = new Date(retDate.getTime() + 60 * 60 * 1000);				
			}						
			log.debug("offset Date: " + retDate);
		}
		return retDate;
	}

update 07-12-2009: The most easy way to convert local time to UTC time

The tricky part is using “Amercias/Indianapolis” or “EST5EDT” instead “EDT” as your local Time zone code. The example method will return correct UTC date. If input date is 2009-02-01 00:00:00 eastern time, then it returns 2009-02-01 05:00:00 but if input date is 2009-07-01 00:00:00, it returns 2009-02-01 04:00:00 because Daylight saving time (UTC-5+1).

Reference:
What is Timezone?
Sources for Time Zone and Daylight Saving Time Data (tz database)

Example code:


/**
* convert local timezone to UTC timezone
* @param inputDate: date needs to be converted
* @param sourceTimezone: local Timezone. This uses tz database Timezone code.
* 
* @return Date 
* e.g. getUTCDate(myLocalDate, "Amercias/Indianapolis")
*/
public Date getUTCDate(Date inputDate, String sourceTimeZone) {
    	Date d = null;
    	try{
    		if (inputDate == null) return d;
    		d= new Date();
	    	SimpleDateFormat sourceFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    	sourceFormatter.setTimeZone(TimeZone.getTimeZone(sourceTimeZone));
	    	String sourceDate = sourceFormatter.format(inputDate);	
	    	SimpleDateFormat destinationFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		destinationFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
		String result = destinationFormatter.format(inputDate);			
		d = sourceFormatter.parse(result);		
    	}catch(Exception e) {
    		e.printStackTrace();
    	}
	return d;
}
About these ads