I'm working on a Vue project and I have a textfield that takes "date-time" to string variable like this DD-MM-YYYY.
I want to convert it to MySQL format (YYYY-MM-DD)
Example input: 24-05-2022
Example output: 2022-05-24
So since
dateInput: '24-05-2022'
dateInput.split("").reverse().join("")
Would change the dateInput
value to:
2202-50-42
I'm wondering how to reverse the string without affecting numbers next to eachother?
EDIT -------------------------------------------------------------------------------------------------------
Forgot to mention I'm using NuxtJs with Vue so the syntax is a little different.
Works now with:
Data
dateInput: '24-05-2022',
array: [],
newDate: ''
Methods
reverseDate () {
this.array = this.dateInput.split('-')
this.newDate = this.array[2] '-' this.array[1] '-' this.array[0]
}
Created
this.reverseDate()
CodePudding user response:
Try below:
let dateInput = '24-05-2022';
let array = dateInput.split("-");
let newDate = `${array[2]}-${array[1]}-${array[0]}`;
console.log(newDate);
CodePudding user response:
Your first try was close to be correct, you just missed including the '-'. This code would also work:
let dateInput = '24-05-2022';
let reversed = dateInput.split('-').reverse().join('-');
console.log(reversed) // outputs: 2022-05-24
And if you would need a Date object, new Date(reversed)
works like a charm.