HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Converting the DateTime to and from Unix epoch times

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theunixepochtimesandconvertingfromdatetime

Problem

I'm currently working on a thing I needed this feature for. Essentially, these are two methods to convert DateTime objects to and from the Unix epoch time (two methods for each action).

There is a non-nullable, and a nullable version for each conversion.

/// 
/// Converts a DateTime to the long representation which is the number of seconds since the unix epoch.
/// 
/// A DateTime to convert to epoch time.
/// The long number of seconds since the unix epoch.
public static long ToEpoch(DateTime dateTime) => (long)(dateTime - new DateTime(1970, 1, 1)).TotalSeconds;

/// 
/// Converts a long representation of time since the unix epoch to a DateTime.
/// 
/// The number of seconds since Jan 1, 1970.
/// A DateTime representing the time since the epoch.
public static DateTime FromEpoch(long epoch) => new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified).AddSeconds(epoch);

/// 
/// Converts a DateTime? to the long? representation which is the number of seconds since the unix epoch.
/// 
/// A DateTime? to convert to epoch time.
/// The long? number of seconds since the unix epoch.
public static long? ToEpoch(DateTime? dateTime) => dateTime.HasValue ? (long?)ToEpoch(dateTime.Value) : null;

/// 
/// Converts a long? representation of time since the unix epoch to a DateTime?.
/// 
/// The number of seconds since Jan 1, 1970.
/// A DateTime? representing the time since the epoch.
public static DateTime? FromEpoch(long? epoch) => epoch.HasValue ? (DateTime?)FromEpoch(epoch.Value) : null;


And here are the relevant unit tests:

```
[TestMethod, TestCategory("Date Time Extensions Tests")]
public void EpochToDateTime_0()
{
var expected = new DateTime(1970, 1, 1, 0, 0, 0, 0);
var input = 0;

var result = DateTimeExtensions.FromEpoch(input);

Assert.AreEqual(expected, result);
}

[TestMethod, TestCategory("Date Time Extensions Tests")]
public void DateTimeToEpoch_1970_1_1_0_0_0_0()
{
var expected = 0;
var input = new DateTime(1970, 1,

Solution

Note that DateTimeOffset.ToUnixTimeSeconds and DateTimeOffset.FromUnixTimeSeconds exist as of .NET 4.6.

Consider using those instead.

If you really need a nullable, you can still wrap the framework methods in an extension method.

Also, generally you should be using DateTimeOffset instead of DateTime unless you explicitly want to ignore timezones (e.g. local noon regardless of timezone). (Somewhat debatable, see comments. Still, as long as you make sure you work in UTC then converting between DateTime and DateTimeOffset shouldn't be a problem for Unix time conversion - and certainly no more than it would be a problem with manual calculations.)

Context

StackExchange Code Review Q#125275, answer score: 10

Revisions (0)

No revisions yet.