I have two dates:
var first = '21-11-2012';
var second = '03-11-2012';
What is the best way to format it like this:
var first = '2012-11-21';
var second = '2012-11-03';
Should I use jQuery or simply JavaScript?
I have two dates:
var first = '21-11-2012';
var second = '03-11-2012';
What is the best way to format it like this:
var first = '2012-11-21';
var second = '2012-11-03';
Should I use jQuery or simply JavaScript?
You don't need jQuery for this, simply use JavaScript like so:
function formatDate(d){
return d.split('-').reverse().join('-');
}
Although if you want more reusable code consider using the JavaScript Date Object.
No need to be thinking of jQuery for basic string manipulation: the standard JS String methods are more than adequate, which (I assume) is why jQuery doesn't actually have equivalent methods.
A regex .replace()
or the split/reverse/join concept in the other answers can both do it in one line. I'd recommend getting familiar with the methods at the MDN page I linked to, but meanwhile:
first = first.replace(/^(\d\d)-(\d\d)-(\d\d\d\d)$/,"$3-$2-$1");
(Same for second
- encapsulate in a function if desired.)
This uses a regular expression to match the different parts of the date and reverse them.
UPDATE - As requested, an explanation of the regex I used:
^ // match beginning of string
(\d\d) // match two digits, and capture them for use
// in replacement expression as $1
- // match the literal hyphen character
(\d\d) // match two digits, and capture for use as $2
- // match the literal hyphen character
(\d\d\d\d) // match four digits, and capture for use as $3
$ // match end of string
Because the pattern matches from beginning to end of string the whole string will be replaced. The parts of the expression in parentheses are "captured" and can be referred to as $1, $2, etc. (numbered in the order they appear in the expression) if used in the replacement string, so "$3-$2-$1"
reverses the order of these captured pieces and puts hyphens between them. (If the input string didn't meet that format the regex would not match and no replacement would be made.)
first=first.split("-").reverse().join("-")
second=second.split("-").reverse().join("-")