Javascript DATE 和 C# date - 最好的解决方案是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10108911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:44:17  来源:igfitidea点击:

Javascript DATE and C# date - what is the best solution?

c#javascriptjsondatetime

提问by test

I am getting a date from server side C# using the following code:

我使用以下代码从服务器端 C# 获取日期:

DateTime d1 = new DateTime(1970, 1, 1);
DateTime d2 = (DateTime)c.ccdTimestamp2;
long x = new TimeSpan(d2.Ticks - d1.Ticks).TotalMilliseconds;

When I get my code on the javascript side:

当我在 javascript 端获取我的代码时:

function (timestamp) {
    alert("testing :" + new Date(timestamp))
}

This gives me a fully formatted date but it does not bring the time of my timezone since if it is 17.15 here, it provides me with 19.15 GMT +2 !

这给了我一个完全格式化的日期,但它没有带来我的时区时间,因为如果这里是 17.15,它为我提供了 19.15 GMT +2 !

At first I simply tried to pass my c# timestamp, without any of the code above and found this question: How do I format a Microsoft JSON date?But I have no idea what JSON is and I couldn't derive what I can do! Is it easier to use JSON? If so can anyone guide me? Thank you very much

起初我只是尝试传递我的 c# 时间戳,没有上面的任何代码,并发现了这个问题:如何格式化 Microsoft JSON 日期?但我不知道 JSON 是什么,我无法推导出我能做什么!使用 JSON 是否更容易?如果是这样,有人可以指导我吗?非常感谢你



Edit: The Solution - I did not use universal time on the server side. I left server side code as it is. All I did is this:

编辑:解决方案 - 我没有在服务器端使用世界时。我保留了服务器端代码。我所做的就是这样:

new Date(timestamp).toUTCString()

回答by ntziolis

What you should do is:

你应该做的是:

  • Always use UTC times on the server
  • Send UTC times to the browser as unit time stamps as you do now
  • Convert the time stamp to local time in the browser
  • 始终在服务器上使用 UTC 时间
  • 像现在一样将 UTC 时间作为单位时间戳发送到浏览器
  • 在浏览器中将时间戳转换为本地时间

The timestamp used represents: 2012-04-11T15:46:29+00:00:

使用的时间戳表示2012-04-11T15:46:29+00:00

var d = new Date ( 1334159189000 );
// gives you back 2012-04-11T15:46:29+00:00 in a slightly different format, but the timezone info matches UTC/GMT+0
d.toUTCString();
// gives you back your local time
d.toLocaleString();

Just created a jsfiddle to show that it does what it is supposed to:
http://jsfiddle.net/t8hNs/1/

刚刚创建了一个 jsfiddle 来表明它做了它应该做的事情:http:
//jsfiddle.net/t8hNs/1/

?

?

回答by Kasidesh Yontaradidthaworn

use

利用

var currentDate = new Date();
//get off set from your browser
var offset = Date.getTimezoneOffset();

回答by L.B

you can use JavaScriptSerializer

你可以使用JavaScriptSerializer

string json = new JavaScriptSerializer().Serialize(DateTime.Now);