I was recently working on a Salesforce integration with Stripe when I came across something new to me. The date/time stamp for the charge showed up as a number (see image below). It represents Unix time (sometimes called a Unix timestamp), which is the number of seconds that have elapsed since January 1, 1970, 00:00:00 UTC (the Unix epoch).
You can think of Unix time as a fast & efficient way of representing a date and time.
But to capture the data in Salesforce, I needed to convert the Unix time back to a DateTime field. Fortunately, this is easily done using Apex DateTime methods or Salesforce formula functions.
How to Convert Between Unix Time and Salesforce DateTime in Apex
In Apex, we need to use DateTime class methods. To convert Unix time to a DateTime value we need to use the newInstance(milliseconds) method. Notice here that the method parameter is in milliseconds but Unix time is in seconds. So to get the correct result, we need to multiply the Unix time by 1000. It’s also worth pointing out that we need to use the data type Long (as opposed to Integer).
Long unixTime = 1716435835; // Unix time
System.debug('unixTime: ' + unixTime);
Long unixTimeMilliseconds = unixTime * 1000; // convert to milliseconds
DateTime dateTimeValue = DateTime.newInstance(unixTimeMilliseconds);
System.debug('dateTimeValue: ' + dateTimeValue);
To go in the opposite direction, where we need to convert a DateTime field to Unix time, we need to use the getTime() method. But in this case, we need to remember to divide the final result by 1000 so that we end up with seconds instead of milliseconds.
DateTime dateTimeNow = DateTime.now();
System.debug('Current DateTime: ' + dateTimeNow);
Long unixTimeNow = dateTimeNow.getTime() / 1000;
System.debug('Unix Time: ' + unixTimeNow);
How to Convert Between Unix Time and Salesforce DateTime Using Salesforce Functions
If you thought using Apex to convert between the two was easy, it’s even easier using Salesforce formula functions. That’s because you don’t even have to worry about converting between seconds and milliseconds. There are just two straightforward formula functions:
- FROMUNIXTIME(seconds)
- UNIXTIMESTAMP(DateTime).
FROMUNIXTIME takes in seconds as a parameter and returns the DateTime. UNIXTIMESTAMP takes in a DateTime and returns the Unix time.
Here’s how I recently used them both in two separate flow formula resources. Note the data type for each:
And if you want to test this flow yourself, go to the Unix Time/DateTime Conversion Calculator.
Did this post help you solve a problem? If so, leave a comment!