Skip to content

Commit

Permalink
add Extentions for UnixTimeStamp.
Browse files Browse the repository at this point in the history
  • Loading branch information
arichika committed Dec 21, 2015
1 parent 00944f1 commit 99d326c
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 6 deletions.
30 changes: 30 additions & 0 deletions src/JwtDnx/JwtDnxExtentions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System;
namespace JwtDnx
{
public static class JwtDnxExtentions
{
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

/// <summary>
/// Convert from .NET DateTime to UnixTimeStamp.
/// (FYI in NET4.6 -> https://msdn.microsoft.com/en-us/library/system.datetimeoffset.tounixtimeseconds.aspx)
/// </summary>
/// <param name="dateTimeUtc">DateTimeUtc</param>
/// <returns>UnixTimeStamp</returns>
public static long ToUnixTimeSeconds(this DateTime dateTimeUtc)
{
return (long)Math.Round((dateTimeUtc.ToUniversalTime() - UnixEpoch).TotalSeconds);
}

/// <summary>
/// Convert from UnixTimeStamp to .NET DateTime.
/// (FYI in NET4.6 -> https://msdn.microsoft.com/en-us/library/system.datetimeoffset.tounixtimeseconds.aspx)
/// </summary>
/// <param name="unixTimeStamp">UnixTimeStamp</param>
/// <returns>DateTime by Utc</returns>
public static DateTime ToDateTiemUtc(this long unixTimeStamp)
{
return UnixEpoch.AddSeconds(unixTimeStamp);
}
}
}
31 changes: 31 additions & 0 deletions test/JwtDnxTests/JwtDnxExtentionsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using JwtDnx;
using Xunit;

namespace JwtDnxTests
{
public class ExtentionsTests
{

private static DateTime _netDateTimeUtc = new DateTime(2038, 01, 19, 03, 14, 07, DateTimeKind.Utc);
private static long _unixTimestamp = 2147483647L;

[Fact]
public void Should_Convert_from_DateTime_to_UnixTime()
{
long result = _netDateTimeUtc.ToUnixTimeSeconds();
Assert.Equal(result, _unixTimestamp);
}

[Fact]
public void Should_Convert_from_UnixTime_to_DateTime()
{
DateTime result = _unixTimestamp.ToDateTiemUtc();
Assert.Equal(result, _netDateTimeUtc);
}
}
}
7 changes: 1 addition & 6 deletions test/JwtDnxTests/project.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
{
"version": "1.0.0-*",
"description": "JwtDnxTests Class Library",
"authors": [ "ax" ],
"tags": [ "" ],
"projectUrl": "",
"licenseUrl": "",
"dependencies": {
"FluentAssertions": "4.1.1",
"JwtDnx": "1.0.0-*",
"JwtDnx": "1.0.1-*",
"xunit": "2.1.0",
"xunit.runner.dnx": "2.1.0-rc1-build204"
},
Expand Down

0 comments on commit 99d326c

Please sign in to comment.