Convert an offset in seconds to Datetime in Apex

Convert an offset in seconds to Datetime in Apex
Photo by Agê Barros / Unsplash

We often come across a challenge where we want to calculate a future (or a past) Date from the current Date based on an offset that are in seconds.

For e.g., in an OAuth flow once we receive an access_token from an authorization_code grant type,  we also get an expiry time in seconds - this is basically the offset/duration after which the access_token will expire. When the access_token expires, the OAuth flow gives an option to refresh the token using refresh_token flow.

Therefore we need to know when the access_token will expire - not in seconds but the Datetime relative to the Datetime when the access_token was generated.

It isn't a very complex calculation but a bit complex for formula field. Here is a sample apex code to calculate the future Datetime offset from current Datetime:

Apex code to convert seconds to Datetime

Integer day = 86400; //24 hours x 60 minutes x 60 seconds
Integer hour = 3600; //60 minutes x 60 seconds
Integer minute = 60; //60 seconds
Integer totalSeconds = Integer.valueOf(expiry); //expiry is the offset in seconds saved in text field
Integer daysout = Integer.valueOf(Math.floor(totalseconds / day));
Integer hoursout = Integer.valueOf(Math.floor((totalseconds - daysout * day)/hour));
Integer minutesout = Integer.valueOf(Math.floor((totalseconds - daysout * day - hoursout * hour)/minute));
Integer secondsout = Integer.valueOf(totalseconds - daysout * day - hoursout * hour - minutesout * minute);
String inpputString ='-''-'+('T'+(':'+(':'+('.'+'000Z';
DateTime resultDateTime = DateTime.valueof(inpputString.replace('T', ' ')); 
About the author
Muralidhar Sampathirao

Muralidhar Sampathirao

Sr Technical Consultant @ Salesforce • With thrdz I am designing the building blocks for Enterprise Applications • Articles, opinions and resources expressed/shared are entirely my personal views.


DZining the building blocks for Enterprise Applications


Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to THR(EA)DZ.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.