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:

system.debug(DateTime.newInstance(1391529600000L));

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));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));