将json结果转换为正确的日期-javascript
您好,我正在尝试将json日期转换回正常的dd/mm/yy日期 如何将Customer.DateOfBirth dd/mm/yy从json日期转换回正常日期 这是我的密码将json结果转换为正确的日期-javascript,javascript,json,Javascript,Json,您好,我正在尝试将json日期转换回正常的dd/mm/yy日期 如何将Customer.DateOfBirth dd/mm/yy从json日期转换回正常日期 这是我的密码 // parse the date var Birth = Customer.DateOfBirth; if (Birth != '') { // get the javascript date object
// parse the date
var Birth = Customer.DateOfBirth;
if (Birth != '') {
// get the javascript date object
Birth = DateFromString(Birth, 'dd/MM/yyyy');
if (Birth == 'Invalid Date') {
Birth = null
}
else {
// get a json date
Birth = DateToString(Birth);
//REPLACE JSON DATE HERE WITH NORMAL DATE??
}
}
任何建议都很好。
谢谢如果您可以将JSON表示形式更改为
yyyy/mm/dd
,那么您可以使用
Birth = new Date(Birth);
如果必须使用当前格式,则必须进行一些手动解析
提取日/月/年部分,并以预期格式创建字符串
var parts = Birth.split('/'),
day = parts[0],
month = parts[1],
year = parts[2],// you need to find a way to add the "19" or "20" at the beginning of this since the year must be full for the parser.
fixedDate = year + '/' + month + '/' + day;
Birth = new Date(fixedDate);
您可以从
mm/dd/yyyyy
字符串创建Date
对象,因此,如果您的字符串排序为dd/mm/yyyyy
,您将得到无效日期
错误,或者更糟糕的是,创建日期错误的日期对象(1月10日而不是10月1日)
因此,在将字符串传递给Date
构造函数之前,需要交换字符串的dd
和mm
部分:
var datestr = Customer.DateOfBirth.replace(/(\d+)\/(\d+)\/(\d+)/,"$2/$1/$3");
Birth = new Date( datestr );
您还可以按yyyy/mm/dd
顺序传递字符串:
var datestr = Customer.DateOfBirth.split('/').reverse().join('/');
Birth = new Date( datestr );
那么问题是什么呢?
Birth
变量的格式是什么,DateFromString
和DateFromString
函数的作用是什么?customer.DateOfBirth是dd/mm/yy。。我的问题是,在我需要转换它的时候,它会保存为json日期。我不知道该怎么做。。