user1261774
user1261774

Reputation: 3695

Javascript to format date value

I am trying (and failing!) to format my date output using javascript, so I am asking for some help.

The date format is 2013-12-31 (yyyy-mm-dd), but I want to display the date as 12-2013 (mm-yyyy).

I have read many posts, but I am now just confused.

Here is the call to the javascript function:

changeDateFormat($('#id_award_grant_date').val()),

Here is the javascript function:

 function changeDateFormat(value_x){


 }

Upvotes: 2

Views: 220

Answers (4)

Bill Criswell
Bill Criswell

Reputation: 32941

You can do this pretty easily with split and join.

var yyyymmdd = '2013-12-31'.split('-'),
    mmyyyy = [ yyyymmdd[1], yyyymmdd[0] ].join('-');

console.log('The date is: ', mmyyyy );

Upvotes: 1

qiu-deqing
qiu-deqing

Reputation: 1333

function changeDateFormat(str) {
    var reg = /(\d+)-(\d+)-(\d+)/;
    var match = str.match(reg);
    return match[2] + "-" + match[1];
}

http://jsfiddle.net/wZrYD/

Upvotes: 1

adeneo
adeneo

Reputation: 318332

What you have is just a string, so just split it and put it back together in the wanted format

var date     = '2013-12-31',
    parts    = date.split('-'),
    new_date = parts[1]+'-'+parts[0];

FIDDLE

Upvotes: 4

Matt
Matt

Reputation: 20796

var d = '2013-12-31'
var yyyymmdd = d.split('-')
var mmyyyy = yyyymmdd[1]+'-'+yyyymmdd[0]; // "12-2013"

Upvotes: 3

Related Questions