I have a string "26-08-2016" and I want to convert it to "2016-08-26". I prefer when possible to do this using the date object. But I am afraid some regex solution is only available?
4 Answers
Did you alredy try to use moment.js?
var mydate = moment("26-08-2016" , "DD-MM-YYYY").format("YYYY-MM-DD");
1 Comment
Ingvi Jónasson
No but this looks awesome.
The Dateobject does expose an API which allows you to get certain values from the object such as date, month, hour, and timezone, which can be used to format a date string.
Simple formatting example using Date object methods.
var date = new Date();
var output = [date.getFullYear(), date.getMonth()+1, date.getDate()].join('-');
console.log( output ); //2016-8-26
The better way is probably to write a formatting function like so:
function formatDate(now) {
var year = now.getFullYear();
var month = now.getMonth()+1;
var date = now.getDate();
//Add '0' to month if less than 10
month = (month.toString().length < 2)
? "0"+month.toString()
: month;
return [year, month, date].join('-');
//return `${year}-${month}-${date}`; if you're using ES6
}
var now = new Date();
console.log(
formatDate(now)
); // 2016-08-26
All available methods are found here at mozilla docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth
"26-08-2016".split('-').reverse().join('-')