Bruce
Bruce

Reputation: 691

Convert cron expression from one timezone to another one

I am looking for a 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 course this will need to convert 0 10 22 2,4 * ? to this user's timezone)

Any help is appreciated

Upvotes: 4

Views: 8851

Answers (2)

cezar berardo
cezar berardo

Reputation: 1

You can try it: https://github.com/VidocqH/cron-timezone-convert

install crontzconvert

pip3 install crontzconvert

use it

import crontzconvert

print(crontzconvert.convert('5 13 * * 3', 'Etc/GMT-3', 'Etc/UTC'))

Upvotes: 0

sashimi
sashimi

Reputation: 1304

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).

Upvotes: 0

Related Questions