Skip to content Skip to sidebar Skip to footer

Simple Javascript Date Conversion

I have this - Tue, 03 Apr 2012 05:00:33 GMT Need this - 20120323111106 Google has failed me, I think I just don't know exactly what im searching for so I kept it simple here with t

Solution 1:

Good answer (later edited):

I think this is what you are looking for :

function addZero(val){
    if (parseInt(val) < 10) return "0" + val;
    return val;
}

var dt = new Date("Tue, 03 Apr 2012 05:00:33 GMT");
console.log(dt.getFullYear() + addZero(dt.getMonth()) + addZero(dt.getDay()) + addZero(dt.getHours()) + addZero(dt.getMinutes()) + addZero(dt.getSeconds()))

Initial wrong answer :

var dt = new Date("Tue, 03 Apr 2012 05:00:33 GMT")
var miliseconds = dt.getTime();

I've tested it and my computer converted it automatically to GMT +3 (my timezone), you can play with that according to your timezone.


Solution 2:

Writing a function to parse a string should work for you. By the looks of it, any date string that you currently have will be the same length. If this is the case this should be relatively easy. Just make sure your strings are in this format before you pass them in as arguments.

function parse(string) {
    var out = "yyyymmddhhmmss"
    out.charAt(0) = string.charAt(13);
    out.charAt(1) = string.charAt(14);
    out.charAt(2) = string.charAt(15);
    out.charAt(3) = string.charAt(16);

    //if else statements for each month converting to numbers
    if (string.substring(9,12).equals("Apr")) {
         out.charAt(4) = '0';
         out.charAt(5) = '4';
    }

    out.charAt(6) = string.charAt(18);
    out.charAt(7) = string.charAt(19);

    ...etc for the remaining values

    return out
}

My numbers for character indices may be off, but if you use this idea, it should set you straight. Define a function and pass in the dates in the format you have, and out will come the dates in the format you want.


Post a Comment for "Simple Javascript Date Conversion"