Convert Unix timestamp to Apex datetime

Salesforce Feb 28, 2015

While going through the description, It seems to be a easy task to do but it took one day for me to figure out the solution. So First of all, we will discuss about Unix Timestamp to give you a background.

What is Unix Time?
Unix time, or POSIX time, is a system for describing instants in time, defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970 not counting leap seconds.
It is used widely in Unix-like and many other operating systems and file formats. Due to its handling of leap seconds, it is neither a linear representation of time nor a true representation of UTC.[note 3] Unix time may be checked on most Unix systems by typing date +%s on the command line.
Why we need this conversion??
While doing integration with many systems , you may get unix timestamps as datetimes. Thus a need arises for conversion

How to convert into Apex Datetime??

this will give : 2013-12-14 15:09:10

Note : You may get unix timestamp as 10 digit character or so . To convert it into exact time in Apex, change the time stamp to 13 characters by adding/removing zeros from it's tail
let's take above example, if I try to convert '1387033750' , it will give me 1970-01-17 01:17:13. Adding three Zeros at tail, gave me the exact value

Useful Links:

  1. To know more about Unix time, Please refer : Unix time
  2. To know more about Salesforce Datetime Methods, Please refer : Datetime Methods
  3. To play around with this code, Use calculator at this link to convert datetime into Unix time

Related Tags:

Salesforce