简体   繁体   English

在JavaScript中从SQL Server转换datetime

[英]Convert datetime from sql-server in javascript

I have a datetime in SQL server that i return from a controller method in my MVC project using return json() 我在SQL Server中有一个日期时间,我使用return json()从我的MVC项目中的控制器方法return json()

I get this format in my json-response: 我在json响应中得到了这种格式:

time: "/Date(1409763303817)/"

I try to use this data in a table in my UI with this code: 我尝试通过以下代码在UI的表中使用此数据:

$("#missingTime").html(new Date(data3.time).toDateString());

I get "Invalid Date" in my column. 我在栏中看到“无效日期”。

What am i doing wrong? 我究竟做错了什么?

Edit: Found a solution 编辑:找到了解决方案

new Date(parseInt(data3.time.replace("/Date(", "").replace(")/",""), 10)

The JSON value you have is not a valid number to be parsed into a JavaScript Date object. 您拥有的JSON值不是要解析为JavaScript Date对象的有效数字。 A quick fix would be to strip out the UTC value (the numbers) from your string using a regular expression and pass this to your function (after parsing into a number), like so: 一种快速解决方案是使用正则表达式从字符串中剥离UTC值(数字),并将其传递给函数(在解析为数字之后),如下所示:

var regEx = /\d+/g;
var utcInfo = data3.time.match(regEx);
$("#missingTime").html(new Date(parseInt(utcInfo)).toDateString());

Although you might want to check why your JSON response is giving you the incorrect value in the first place. 尽管您可能想检查一下为什么JSON响应首先为您提供了不正确的值。 The value in the JSON object needs to be as follows in order for your JS code to work: JSON对象中的值必须如下所示,以便您的JS代码起作用:

time: 1409763303817

If you take use of the MVC-Model the Controller-Layer should convert the time into a format the View can handle. 如果您使用MVC模型,则控制器层应将时间转换为视图可以处理的格式。

See, a Time is more than Minutes, Hours and Seconds. 看,时间比分钟,小时和秒还要多。 Its depends on the Timezone the calling Browser physicaly is. 它取决于调用浏览器的物理时区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM