Salmon
Salmon

Reputation: 133

How to convert MySQL DATETIME value to json format in JavaScript

I want to convert the DATETIME value retrieved from MySQL to JSON.

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

The resulting JSON should look like this:

{'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.

Upvotes: 2

Views: 1711

Answers (2)

hex494D49
hex494D49

Reputation: 9235

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

Upvotes: 1

sri
sri

Reputation: 338

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.

Upvotes: 4

Related Questions