2

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){


 }
2
  • 1
    Split the date in parts by - then join the parts as you like. Commented Dec 17, 2013 at 1:33
  • 2
    It might be overkill for what you want to achieve but I really like the javascript date library Moment.js momentjs.com/docs/#/parsing/string-format Commented Dec 17, 2013 at 1:35

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! So easy when you are not a noob like me!
What a lazy programmer like me would do: [parts[1],parts[0]].join("-"); if you have many items to combine.
@user1261774 - hopefully this isn't a datepicker? If it where you should probably be using some of the built in methods instead.
3
var d = '2013-12-31'
var yyyymmdd = d.split('-')
var mmyyyy = yyyymmdd[1]+'-'+yyyymmdd[0]; // "12-2013"

Comments

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

http://jsfiddle.net/wZrYD/

2 Comments

Good stuff, the regex solution here is the only solution here even attempting to validate that the input is numeric. I managed to whittle it down to one line in the function using regex replace jsfiddle.net/wZrYD/2
i learn a lot from your update: 1.strict validate 2.replace() is more elegant(my solution is ugly). thanks for you feedback @MatthewLock :)
1

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 );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.