Convert epoch to datetime in Apex

We get this requirement while coding several time to convert epoch time (Unix time) to Datetime.

First thing, never store a epoch time in Integer and use Long always.

Below given code can be used to convert into datetime:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
system.debug(DateTime.newInstance(1391529600000L));
system.debug(DateTime.newInstance(1391529600000L));
system.debug(DateTime.newInstance(1391529600000L));

To get the epoch from a datetime variable you can just call the getTime() instance method:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Datetime dt = Datetime.now();
Long l = dt.getTime();
system.debug(l);
system.debug(DateTime.newInstance(l));To get the epoch from a datetime variable you can just call the getTime() instance method:
Datetime dt = Datetime.now();
Long l = dt.getTime();
system.debug(l);
system.debug(DateTime.newInstance(l));
Datetime dt = Datetime.now(); Long l = dt.getTime(); system.debug(l); system.debug(DateTime.newInstance(l));To get the epoch from a datetime variable you can just call the getTime() instance method: Datetime dt = Datetime.now(); Long l = dt.getTime(); system.debug(l); system.debug(DateTime.newInstance(l));
Datetime dt = Datetime.now();
Long l = dt.getTime();
system.debug(l);
system.debug(DateTime.newInstance(l));To get the epoch from a datetime variable you can just call the getTime() instance method:

Datetime dt = Datetime.now();
Long l = dt.getTime();
system.debug(l);
system.debug(DateTime.newInstance(l));