开发者

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 - unfor开发者_Python百科tunately I can't mark them both as answers, but I wish I could!


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);


A datetime object represents an instant in time and is usually represented internally as the number of milliseconds since the epoch. In JavaScript to get this value for the current time it is easier to use

new Date().getTime()

Now you just have a number (or a string containing a number) which you can pass to your C# application and construct a DateTime object from.

For that I can refer you to C# convert UTC int to DateTime object (Jon Skeet has an answer for it.) :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜