3

I want to change YYYY-MM-DD HH:MM:SS to MM-DD-YYYY

Example: I have a string which represents a date in this format: 2013-06-15 03:00:00

I want to change this string into 06-15-2013 using JavaScript.

Is there any library to do this? or should i just use JavaScript?

Linus Caldwell
  • 10,908
  • 12
  • 46
  • 58
Sorin Vladu
  • 1,768
  • 3
  • 21
  • 37
  • A *library*? A simple regular expression should be sufficient. – Zeta Jun 10 '13 at 20:59
  • why you want to do it by javascript? you can do it just by SampleDateFormat – Souad Jun 10 '13 at 21:03
  • 1
    @Souad: Is there any reason why you encourage to use a Java facility in a JavaScript specific question? – Zeta Jun 10 '13 at 21:06
  • is this question what you really meant? because your title is misleading....Javascript change date format from YYYY-MM-DD HH:MM:SS to MM-DD-YYYY – abc123 Jun 10 '13 at 21:13

3 Answers3

9
function change(time) {
    var r = time.match(/^\s*([0-9]+)\s*-\s*([0-9]+)\s*-\s*([0-9]+)(.*)$/);
    return r[2]+"-"+r[3]+"-"+r[1]+r[4];
}
change("2013-06-15 03:00:00");
VeeTheSecond
  • 3,086
  • 3
  • 20
  • 16
0

see moment.js.. i found it very useful http://momentjs.com/

Gokul Kav
  • 839
  • 1
  • 8
  • 14
0

DEMO: http://jsfiddle.net/abc123/f6k3H/1/

Javascript:

var d = new Date();
var c = new Date('2013-06-15 03:00:00');

alert(formatDate(c));
alert(formatDate(d));

function formatDate(d)
{
    var month = d.getMonth();
    var day = d.getDate();
    month = month + 1;

    month = month + "";

    if (month.length == 1)
    {
        month = "0" + month;
    }

    day = day + "";

    if (day.length == 1)
    {
        day = "0" + day;
    }

    return month + '-' + day + '-' + d.getFullYear();
}

Since this doesn't use RegEx you'll notice some weirdness....Examples:

d.getMonth() + 1

this is because getMonth is 0 indexed....

 day = day + "";

    if (day.length == 1)
    {
        day = "0" + day;
    }

this is because hours, seconds, minutes all return 1 digit when they are 1 digit...this makes them return a leading 0. The same can be done to Month and Day if desired.

abc123
  • 17,855
  • 7
  • 52
  • 82
  • 1
    Whelp. That's an off-topic answer, the question was how to modify an existing time string, not how to create a new one with the given format. – Zeta Jun 10 '13 at 21:10
  • valid point...when reading it I changed some words apparently, because i didn't think anyone would want to do what he is asking...mainly because of the question title "Javascript change date format from YYYY-MM-DD HH:MM:SS to MM-DD-YYYY", i've offered an edit to his question, depending on his response I will likely delete this answer. – abc123 Jun 10 '13 at 21:12