2

Good day,

I'm trying to check if an token expiration date is already expired. I'm using JWT in generating my token. I'm able to check in my javascript environment if my token is still valid by using this code.

if (decodedToken.exp < new Date().getTime() / 1000) {
    alert("Session expired);
}

// decodedToken.exp returns a value like "1556797243"

But my problem is, I don't know how to validate using C# code if the token is already expired.

I tried something like this,

// suppose I have a value of "1556797243"
var expirationDate = DateTime.ParseExact(expiration, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

But it doesn't work.

Chris Catignani
  • 5,040
  • 16
  • 42
  • 49
AppleCiderYummy
  • 369
  • 1
  • 7
  • 20

2 Answers2

9

.NET has a built-in way to parse a Unix timestamp, but it's on DateTimeOffset, not DateTime, as you might expect:

var expirationTime = DateTimeOffset.FromUnixTimeSeconds(expiration).DateTime;

If expiration is a string you'd need to parse it into a long first:

var expirationTime = DateTimeOffset.FromUnixTimeSeconds(long.Parse(expiration)).DateTime;
EM0
  • 5,369
  • 7
  • 51
  • 85
  • But there would be no problem right? whether I get the datetimeoffset rather than datetime? – AppleCiderYummy May 01 '19 at 12:43
  • The last `.DateTime` part converts a `DateTimeOffset` to a `DateTime` – EM0 May 01 '19 at 13:17
  • 1
    Though not completely wrong to use `.DateTime`, you'd be better off using `.UtcDateTime`, which properly sets the `.Kind` of the result to `DateTimeKind.Utc` instead of `DateTimeKind.Unspecified`. – Matt Johnson-Pint May 01 '19 at 20:56
3

You can use this function to convert from unixTime to DateTime

public static class DateUtil
    {
    private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

    public static DateTime FromUnixTime(long unixTime)
    {
        return Epoch.AddMilliseconds(unixTime).ToLocalTime();
    }
}
var expirationDate  = DateUtil.FromUnixTime(yourtime);
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62