1

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?

More Detailed Explanation:

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!

cup_of
  • 5,033
  • 5
  • 27
  • 67
  • hello I am unsure where you are getting the -2030 and 1970 from – cup_of Jul 24 '17 at 01:43
  • What is the actual data type of `tdate`? The lines of code you're showing make it look like you're subtracting integers, which has nothing to do with a date. Is `tdate` an actual date object? A string? Something else? If it's a date object, why not just format it how you want it when you output it? – David Jul 24 '17 at 01:45
  • oh yes sorry I need a string! – cup_of Jul 24 '17 at 01:46
  • @david the datatype of tdate is a string. – cup_of Jul 24 '17 at 01:47
  • @david I didnt put in my full code, only a small snippet i thought was required to answer the question. Basically I am using an api that needs a certain format and the way i have the user input in a date does not match the api's format – cup_of Jul 24 '17 at 01:48
  • Possible duplicate of [How to format a JavaScript date](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – Rob Jul 24 '17 at 01:50

4 Answers4

5

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)
guest271314
  • 1
  • 10
  • 82
  • 156
4

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")
)
Psidom
  • 171,477
  • 20
  • 249
  • 286
2

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)
charlietfl
  • 164,229
  • 13
  • 110
  • 143
1

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);
Dij
  • 9,501
  • 4
  • 15
  • 34
  • Thanks for the answer, I upvoted you but accepted someone elses answer because they found a solution with one less variable – cup_of Jul 24 '17 at 01:59