C# - Converting Unix times(epoch time) to/from Local time

The Unix time is given as seconds since the epoch: the number of seconds (not counting leap seconds) that have passed since 00:00:00 Coordinated Universal Time (UTC), or Thursday, January 1st, 1970.
Following are the methods to convert the Unix time to/from Local time

Before .Net framework 4.6

Before .Net 4.6, there is no method given the framework for converting Unix time to local time and vice versa. So we need to implement our own. As per the definition of Unix time, it is the number of seconds since 1st January 1970, 00:00:00 UTC. Following are the methods
// Local Time --> Unix Time
private long ToUnixTime(DateTime dateTime)
{
 var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
 return (long)(dateTime.ToUniversalTime() - epoch).TotalSeconds;
}

// Unix Time --> Local Time
private DateTime FromUnixTime(long unixDateTime)
{
 var timeSpan = TimeSpan.FromSeconds(unixDateTime);
 return new DateTime(timeSpan.Ticks).ToLocalTime();
}

From .Net framework 4.6

.NET 4.6 introduces 4 new methods to DateTimeOffset class for converting Datetime to or from Unix time.
  1. static DateTimeOffset FromUnixTimeSeconds(long seconds)
  2. static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds)
  3. long ToUnixTimeSeconds()
  4. long ToUnixTimeMilliseconds()

// Local Time --> Unix Time
private long ToUnixTime(DateTime dateTime)
{
 var dateTimeOffset = new DateTimeOffset(dateTime);
 return dateTimeOffset.ToUnixTimeSeconds();
}


// Unix Time --> Local Time
private DateTime FromUnixTime(long unixDateTime)
{
 return DateTimeOffset.FromUnixTimeSeconds(unixDateTime).DateTime.ToLocalTime();
}
Happy Coding! 😊😊

Gopikrishna

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment