0

I want to create a function that converts all date formats into single date format (yyyy-mm-dd).

function taskDate(dt){
    console.log(dt)
}
var dt = new Date("15-10-2022")
var d = dt.getDate();
var m = dt.getMonth() + 1;
var y = dt.getFullYear();
var dateString =  y + '-' + (m <= 9 ? '0' + m : m) + "-" + (d <= 9 ? '0' + d : d);
taskDate(dateString)

the problem occurred in dd-mm-yyyy format its converts day into month automatically and when the day is more than 12 its returns, Nan.

enter image description here

ksav
  • 20,015
  • 6
  • 46
  • 66

2 Answers2

1

To convert a date to the yyyy-MM-dd format, the Swedish locale can be used.

By the way, your date is actually invalid. Refer https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date

var dt = new Date(2022, 9, 15); // the 2nd arg is monthIndex (starts from 0)
var str = dt.toLocaleString('sv-SE'); // Swedish locale
console.log(str);
Nice Books
  • 1,675
  • 2
  • 17
  • 21
0

You input date string is invalid to Date.

var dt = new Date('15-10-2022');
console.log(dt)

You can swap day of month and month and it will work as expected as:

var dt = new Date('10-15-2022');
console.log(dt);

FINAL CODE

function taskDate(dt) {
    console.log(dt);
}
var dt = new Date('10-15-2022');
var d = dt.getDate();
var m = dt.getMonth() + 1;
var y = dt.getFullYear();
var dateString =
    y + '-' + (m <= 9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
taskDate(dateString);

To convert from dd-mm-yyyy to mm-dd-yyyy as:

const date = '15-10-2022';
const [dd, mm, yy] = date.split('-');
const newDate = [mm, dd, yy].join('-');
console.log(newDate);
DecPK
  • 24,537
  • 6
  • 26
  • 42