简体   繁体   中英

How to offset Date to adjust to DST in Java

I have a job written in Java which runs on a specified time every day on that timezone. For example if I started the job for the first time at 0800 hrs it must alwas run the job on the same time everyday. This works fine if the timezone does not follow DST. But it breaks if it follows DST.

For example if I started my job for the first time in 0800 PST, it must always run in 0000 hrs in UTC as long as DST is not in effect but should move to 2300 hrs UTC the previous day if DST is in effect. How do I adjust my job start time programatically for these DST changes.

My input looks like this:

String startdate = "2012-06-16T08:00:00"
String timeZone = "PST";

These will be constants located in a config file, and once set cannot be modified. The input will PST regardless of whether DST is in effect or not.

So if the current timezone is in PST it will run on 0000 hrs UTC 2012-06-16 or else it will run on 2300 hrs UTC 2012-06-15.

How do I achieve this.

Note: This is not a homework question and I come from a region that does not follow DST, so it is a bit confusing for me.

Thanks in advance.

I don't know how you are scheduling your jobs, but if you compute the next execution date manually, you can use java.util.Calendar as follows:

TimeZone tz = TimeZone.getTimeZone( timeZone );
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss" );
dateFormat.setTimeZone( tz );
Calendar cal = Calendar.getInstance();
cal.setTimeZone( tz );
cal.setTime( dateFormat.parse( startdate ) );

Then after each execution of the job, you can compute the next run time of the job:

cal.add( Calendar.DAY_OF_YEAR, 1 );

This adds one calendar day, not 24 hours. So if the start date was 8am local time, then it will continue to run at 8am local time even during DST. Calendar will take care of the DST conversion for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM