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
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 = System.now().yearGmt()+'-'+System.now().monthGmt()+'-'+(System.now().dayGmt()+daysout)+'T'+(System.now().hourGmt()+hoursout)+':'+(System.now().minuteGmt()+minutesout)+':'+(System.now().secondGmt()+secondsout)+'.'+'000Z'; DateTime resultDateTime = DateTime.valueof(inpputString.replace('T', ' '));