简体   繁体   English

如何在Java中抵消日期以调整为DST

[英]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. 我有一份用Java编写的工作,每天在该时区的指定时间运行。 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. 例如,如果我在0800时首次开始工作,则必须每天都在同一时间运行该工作。 This works fine if the timezone does not follow DST. 如果时区不遵循夏令时,则此方法工作正常。 But it breaks if it follows DST. 但是,如果遵循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. 例如,如果我第一次在0800 PST开始工作,只要DST无效,它就必须始终在UTC 0000小时运行,但如果DST生效,则应该在前一天移至UTC 2300 hr。 How do I adjust my job start time programatically for these DST changes. 如何针对这些DST更改以编程方式调整我的工作开始时间。

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. 不管DST是否生效,输入都将是PST。

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. 因此,如果当前时区为PST,则它将在UTC 2012-06-16的0000小时运行,否则,它将在UTC 2012-06-15的2300个小时的时间运行。

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. 注意:这不是作业问题,我来自不遵循DST的地区,所以这对我来说有点令人困惑。

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: 我不知道您如何安排工作,但是如果您手动计算下一个执行日期,则可以使用java.util.Calendar ,如下所示:

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. 这将增加一个日历日,而不是24小时。 So if the start date was 8am local time, then it will continue to run at 8am local time even during DST. 因此,如果开始日期是当地时间上午8点,那么即使在夏令时期间,它也将继续在当地时间上午8点运行。 Calendar will take care of the DST conversion for you. 日历将为您处理DST转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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