Ryo
Ryo

Reputation: 1035

JavaScript - Convert date stirng yyyyMMddHHmmss to date object yyyy-MM-dd HH:mm:ss

I have this date : 2014071109080706ICT

I need to convert it to Date object in JS I tried to create new object new Date("2014071109080706ICT") but I get error Invalid date I also tried cut date string to "20140711090807" and create new Date object but it always generate error : Invalid date How can i do it ?

Upvotes: 0

Views: 7613

Answers (2)

jack
jack

Reputation: 82

You can try to use moment.js . http://momentjs.com

There are some examples in docs page. One of them is:

moment("2010-10-20 4:30 +0000", "YYYY-MM-DD HH:mm Z");

http://momentjs.com/docs/#/parsing/

You can try:

moment("20140711090807+0600", "YYYYMMDDHHmmssZZ"); I think "06ICT" is the timezone info.

Upvotes: 4

Yuliam Chandra
Yuliam Chandra

Reputation: 14640

You just need to slice the string for each segment and create the date object based on those parts.

var str = "20140711090807";
var year = str.substring(0, 4);
var month = str.substring(4, 6);
var day = str.substring(6, 8);
var hour = str.substring(8, 10);
var minute = str.substring(10, 12);
var second = str.substring(12, 14);
var date = new Date(year, month-1, day, hour, minute, second);

PS: month index is between 0 and 11 so you need to subtract it by 1.

Upvotes: 2

Related Questions