简体   繁体   English

如何在JavaScript中将MySQL DATETIME值转换为json格式

[英]How to convert MySQL DATETIME value to json format in JavaScript

I want to convert the DATETIME value retrieved from MySQL to JSON. 我想将从MySQL检索到的DATETIME值转换为JSON。

Tue Aug 19 2014 16:55:01 GMT+0800 (CST)

The resulting JSON should look like this: 生成的JSON应该如下所示:

{'year': yyyy, 'month': MM, 'day': dd, 'hour': hh, 'minute': mm, 'second': ss, 'GMT': GMT}

Regular expression seems to be too complex. 正则表达式似乎太复杂了。 I don't know how to perform the conversion. 我不知道如何执行转换。

You could do something like: 您可以执行以下操作:

var d = new Date("Tue Aug 19 2014 16:55:01 GMT+0800 (CST)");
var year = d.getFullYear();
var date = d.getDate();     //so on so forth.

All the date objects are explained here . 说明所有日期对象。 These variables can then be used in your json object. 然后可以在您的json对象中使用这些变量。

It can be done using regular expression as well. 也可以使用正则表达式来完成。 Like in the following snippet. 就像下面的代码片段一样。

var s = 'Tue Aug 19 2014 16:55:01 GMT+0800 (CST)';
var p = /(\w+)\s(\w+)\s(\d+)\s(\d+)\s(\w+):(\d+):(\d+)\s(\w+).*/;

console.log(s.replace(p, "{'year': $4, 'month': $2, 'day': $1, 'hour': $5, 'minute': $6, 'second': $7, 'GMT': $8}"));

Working jsBin 工作jsBin

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

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