Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

c# - Convert JSON dates without timezone

I have a webservice that returns for example a DateTime object: DepartureDate. I use ajax to fetch this and in my view I convert the JSON date string to a javascript date object with this function:

function convertToDate(jsonDate) {
    return eval("new " + jsonDate.substring(1, jsonDate.length - 1));
}

The problem is that new Date() takes the local time on the clients computer in consideration, so clients in different countries get different dates. I want to get the exact date that was returned from the webservice. Is there any easy way to accomplish this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that new Date() takes the local time on the clients computer in consideration

Nope. Creating a new Date using the timestamp constructor takes a UTC time stamp.

For example on my machine in UTC+1:

new Date(0)   // Thu Jan 01 1970 01:00:00 GMT+0100 (CET)

OK, the default toString displays this date as 01:00:00 which looks wrong, but that's actually the correct time. 01:00:00 in UTC+1 is 00:00:00 in UTC, which is the moment described by timestamp 0.

If you want to display the dates you've creating from a timestamp in UTC, use date.toUTCString() or fetch and format the consistuent parts of the date using getUTCFullYear(), getUTCMonth() etc.

Please, though, no eval.

new Date(parseInt(jsonDate.slice(6, -1), 10))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...