Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare a UTC date created in Javascript to a UTC date in C#?

I'm trying to create a UTC date in JavaScript on one server, and pass it via URL querystring to another server, where C# can take that querystring, recognize it as a date and compare it to a new C# UTC date - and it's proving trickier that I though (unless I'm just having one of those days). I don't see any other questions on stackoverflow asking this (in the 'similar titles' or 'similar questions' lists that show while typing a question).

To create the data in JavaScript I'm using the following, based on this w3schools article:

var currentDate = new Date();
var  day = currentDate.getUTCDate();
var month = currentDate.getUTCMonth();
var year = currentDate.getUTCFullYear();
var hours = currentDate.getUTCHours();
var minutes = currentDate.getUTCMinutes();
var seconds = currentDate.getUTCSeconds();
var milliseconds = currentDate.getUTCMilliseconds();

var expiry = Date.UTC(month,day,year,hours,minutes,seconds,milliseconds);

the results looks like this 1311871476074

So, in C# how do I take this value from the querystring and

  1. convert it into a proper date, and
  2. compare it to a C# based UTC DateTime variable?

Any tips, corrections in my logic/code or links to articles would be greatly appreciated.

Kevin

UPDATE
Both the answers below helped me resolve my issue: Luke helped with the C# side of things, and Ray helped with the JavaScript - unfortunately I can't mark them both as answers, but I wish I could!

like image 560
QMKevin Avatar asked Jan 19 '23 02:01

QMKevin


1 Answers

The JavaScript UTC method returns the number of milliseconds since 00:00:00 UTC on 1 January 1970. To convert those milliseconds back to a DateTime in C# you just need to add them onto that original "epoch":

string rawMilliseconds = Request.QueryString["expiry"];

if (string.IsNullOrWhiteSpace(rawMilliseconds))
    throw new InvalidOperationException("Expiry is null or empty!");

long milliseconds;
if (!long.TryParse(rawMilliseconds, out milliseconds))
    throw new InvalidOperationException("Unable to parse expiry!");

DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

DateTime expiry = epoch.AddMilliseconds(milliseconds);
like image 81
LukeH Avatar answered Feb 23 '23 00:02

LukeH