2

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.

1
  • capture groups using parenthesis (...) and replace with $index in final JSON string Commented Aug 19, 2014 at 9:46

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.