'How to "reverse" string that acts as a date time?
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()
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JuanDeLasNieves |
