javascript 将日期字符串转换为 JSON 日期格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27470954/
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-28 07:31:21  来源:igfitidea点击:

convert date string to JSON date format

javascriptjsondate

提问by James

In my javascript i enter date in below format as string

在我的 javascript 中,我以以下格式输入日期作为字符串

12.12.2014

I want to convert to JSON date format like below

我想转换为如下的 JSON 日期格式

/Date(1358866800000)/

How could i achieve this. I tried below code which converts to JSON format but doesnt work.

我怎么能做到这一点。我尝试了下面的代码,它转换为 JSON 格式但不起作用。

function convertToJSONDate(strDate){
var dt = new Date(strDate);
var newDate = new Date(Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate(), dt.getHours(), dt.getMinutes(), dt.getSeconds(), dt.getMilliseconds()));
return '/Date(' + newDate.getTime() + ')/';
}

When i try to use above function like convertToJSONDate("12.12.2014"), i get date like this '/Date(NaN)/

当我尝试使用上述功能时convertToJSONDate("12.12.2014"),我得到这样的日期'/Date(NaN)/

How could i achieve this?

我怎么能做到这一点?

回答by AlexBcn

The string you are passing to Date's constructor is not valid

您传递给 Date 构造函数的字符串无效

function convertToJSONDate(strDate){
  var splitted = strDate.split(".");
  var dt = new Date(splitted[2],splitted[0],splitted[1]);
  var newDate = new Date(Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate(), dt.getHours(), dt.getMinutes(), dt.getSeconds(), dt.getMilliseconds()));
  return '/Date(' + newDate.getTime() + ')/';
}

convertToJSONDate("12.1.2014");

Another simplified version could be:

另一个简化版本可能是:

function convertToJSONDate(strDate){
  var splitted = strDate.split(".");
  //var dt = new Date(splitted[2],splitted[0],splitted[1]);
  var newDate = new Date(Date.UTC(splitted[2], splitted[0], splitted[1]));
  return '/Date(' + newDate.getTime() + ')/';
}

convertToJSONDate("12.1.2014");

回答by stenak

@AlexBcn Great answer, but you need to subtract 1 from the month because months are zero-based.

@AlexBcn 很好的答案,但您需要从月份中减去 1,因为月份是从零开始的。

function convertToJSONDate(strDate){
        var splitted = strDate.split(".");
        var newDate = new Date(Date.UTC(splitted[2], (splitted[1] - 1), splitted[0]));
        return '/Date(' + newDate.getTime() + ')/';
    }
  //console.log(convertToJSONDate("10.01.2018")); 
  //Output: Wed Jan 10 2018 01:00:00 GMT+0100 (Central European Standard Time) 
  //Output without subtraction: Sat Feb 10 2018 01:00:00 GMT+0100 (Central European Standard Time)

回答by user8867350

try like this..

试试这样..

@JsonSerialize(using=CustomJsonDateSerializer.class) @JsonDeserialize(using=CustomJsonDateDeserializer.class)

@JsonSerialize(using=CustomJsonDateSerializer.class) @JsonDeserialize(using=CustomJsonDateDeserializer.class)