Reputation: 287
So i have an input field which gives the value "2020-03-10". I need to convert this to "10-03-2020". I don't even need it to be a date, just a value is okay.
I feel like it is really easy, but I still can't find it with my search queries on here and google :p
<input type="text" id="search-text"/>
Upvotes: 0
Views: 436
Reputation: 714
More universal approach. Converting start when blur input
const dateInput = document.querySelector('input#dateAsText');
console.assert(typeof dataInput === 'undefined', {
msg: 'Not find input'
});
dateInput.addEventListener('change', formateDate);
function formateDate(e) {
const date = new Date(e.target.value);
if (Object.prototype.toString.call(date) === '[object Date]') {
e.target.value = `${date.getDate()}-${(date.getMonth()+1).toString().padStart(2, 0)}-${date.getFullYear()}`;
}
}
<input type="text" id="dateAsText">
Upvotes: 0
Reputation: 945
One way to solve this:
You can use .split('-')
to find all occurrences of -
and split the elements to an array and then use .reverse()
to change the sequence of the elements in array and finally use .join('-')
to convert your array into string separating each element of the string with -
const str = '2020-03-10';
let newStr = str.split('-').reverse().join('-');
https://jsfiddle.net/Lekv7jxu/
--- Edit
You can also make use of arrow functions to create a function and make the code drier
const str = '2020-03-10';
let newStr = str => str.split('-').reverse().join('-');
Upvotes: 0
Reputation: 178350
Regex replace and reorder
let yyyymmdd ='2020-03-10';
const ddmmyyyy = yyyymmdd.replace(/(\d{4})-(\d{2})-(\d{2})/,"$3-$2-$1")
console.log(ddmmyyyy);
Regex and destruct match:
let yyyymmdd ='2020-03-10';
const [_,yyyy,mm,dd] = yyyymmdd.match(/(\d{4})-(\d{2})-(\d{2})/);
const ddmmyyyy = `${dd}-${mm}-${yyyy}`;
console.log(ddmmyyyy);
Upvotes: 0
Reputation: 56
You can split it with '-'. Then put it back together in the order you want. With JavaScript:
function conv(t) {
var mySplit = t.split('-');
return mySplit[2] + '-' + mySplit[1] + '-' + mySplit[0];
}
Upvotes: 0
Reputation: 4879
document.getElementById("search-text").value = "2020-03-10"
console.log(document.getElementById("search-text").value.split('-').reverse().join('-'))
<input type="text" id="search-text"/>
Upvotes: 0
Reputation: 413
You can use:
const value = '2020-03-10'
const formatted = value.split('-').reverse().join('-');
console.log(formatted);
Upvotes: 3