问题
I am looking for the way to convert cron expression from one timezone to another one timezone.
For example, my web-client user is GMT+1200 and my server-side is GMT+0800, while user setting 02:10 to execute task every Tuesday and Thursday, the cron expression will be "0 10 2 3,5 * ?", and I have used code as below, it can get current fire time for user's timezone
CronExpression expr = new CronExpression("0 10 2 3,5 * ?");
System.out.println(expr.getNextValidTimeAfter(new Date()));
System.out.println(expr.getTimeZone());
System.out.println(expr.getExpressionSummary());
System.out.println("=======");
TimeZone tz = TimeZone.getTimeZone("GMT+1200");
expr.setTimeZone(tz);
System.out.println(expr.getNextValidTimeAfter(new Date()));
System.out.println(expr.getTimeZone());
System.out.println(expr.getExpressionSummary());
The getNextValidTimeAfter will print Mon Feb 02 22:10:00 CST 2015, which after setTimeZone(tz);, however the getExpreesionSummary or even getCronExpression() will still be "0 10 2 3,5 * ?", where I want to get string will be "0 10 22 2,4 * ?" and then I can save into DB for next time fire and also another time-zone user to query setting(Of cause this will need to convert "0 10 22 2,4 * ?" to this user's timezone)
Any help is appreciated
回答1:
If you are willing to retain same cron expression, but give contextual calculations based on date timezone (so that user and serverside get next execution based on their timezones for same expression), you may use cron-utils, which provides such functionality. All next/previous execution calculations are contextual to timezone, since release 3.1.1.
They provide an example at the docs:
//Get date for last execution
DateTime now = DateTime.now();
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("* * * * * * *"));
DateTime lastExecution = executionTime.lastExecution(now));
//Get date for next execution
DateTime nextExecution = executionTime.nextExecution(now));
nextExecution value will be calculated for same timezone as reference date (now).
来源:https://stackoverflow.com/questions/28228364/convert-cron-expression-from-one-timezone-to-another-one