Reputation: 6687
Hello I have a function that generates the date with this format:
MM-DD-YYYY
Is there any jquery or javascript trick to convert that value into:
YYYY-MM-DD
?
The function I have generates the date and stored in a variable called tdate
So var tdate = 01-30-2001
I would like to do some jquery or javascript to turn tdate
into:
tdate = 2001-01-30
tdate is a string
Thanks!
Upvotes: 2
Views: 1985
Reputation: 171669
Can slice() up the string and put it back together the way you want it
var tdate = '01-30-2001';
tdate = [tdate.slice(-4), tdate.slice(0,5)].join('-');
// or tdate = tdate.slice(-4) + '-' + tdate.slice(0,5)
console.log(tdate)
Upvotes: 2
Reputation: 9808
you can split the string on '-' and then re arrange the array once and join again to form the date.
var date = "01-30-2001";
var arr = date.split("-");
var revdate = arr.splice(-1).concat(arr.splice(0,2)).join('-');
console.log(revdate);
Upvotes: 1
Reputation: 214967
You can use a little bit regex to capture year, month and day and reorder them:
var tdate = "01-30-2001";
console.log(
tdate.replace(/^(\d{2})-(\d{2})-(\d{4})$/, "$3-$1-$2")
)
Upvotes: 6
Reputation: 1
You can use .split()
, destructuring assignment, termplate literal to place yyyy
, mm
, dd
in any order
var date = "01-30-2001";
var [mm, dd, yyyy] = date.split("-");
var revdate = `${yyyy}-${mm}-${dd}`;
console.log(revdate)
Upvotes: 7