admin管理员组

文章数量:1287628

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!

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!

Share Improve this question edited Jul 24, 2017 at 1:49 cup_of asked Jul 24, 2017 at 1:39 cup_ofcup_of 6,69710 gold badges51 silver badges104 bronze badges 6
  • hello I am unsure where you are getting the -2030 and 1970 from – cup_of Commented Jul 24, 2017 at 1: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 Commented Jul 24, 2017 at 1:45
  • oh yes sorry I need a string! – cup_of Commented Jul 24, 2017 at 1:46
  • @david the datatype of tdate is a string. – cup_of Commented Jul 24, 2017 at 1: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 Commented Jul 24, 2017 at 1:48
 |  Show 1 more ment

4 Answers 4

Reset to default 7

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)

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

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)

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

本文标签: Rearrange date format jQuery or javascriptStack Overflow