Joedie123 Joedie123 - 1 year ago 117
Javascript Question

How to convert string to time?

Currently, I'm parsing a JSON which returns a string like this for time "201610161000"(2016-10-16 10:00). I used Momentjs to parse it like this "moment("201610161000", 'YYYYMMDDHHmm')" The problem is that it takes too much time when I parse it with large data. If I remove it, then it only takes 10ms. Otherwise, it takes 1000 ms with Momentjs. Is there a way that I can convert the string above to time without using Moment? (I have no control to change the time format in JSON)

var inner =, function(n, k) {
return {
x: moment(n.bucket, 'YYYYMMDDHHmm'),
y: n,

Answer Source

This can be done using concatenation and split methods in java-script. Try following approach

var jsonTime = "201610161000".split("");
var parsedDate = jsonTime.slice(0, 4).join("") + "-" + jsonTime.slice(4, 6).join("")+ "-" + jsonTime.slice(6, 8).join("")+ "-" + jsonTime.slice(8, 10).join("")+ ":" + jsonTime.slice(10, 12).join("");
//output : 2016-10-16-10:00
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download