I have a date with the format Sun May 11,2014
. How can I convert it to 2014-05-11
using JavaScript?
None of these answers quite satisfied me. I wanted a cross-platform solution that gave me the day in the local timezone without using any external libraries.
This is what I came up with:
function localDay(time) {
var minutesOffset = time.getTimezoneOffset()
var millisecondsOffset = minutesOffset*60*1000
var local = new Date(time - millisecondsOffset)
return local.toISOString().substr(0, 10)
}
That should return the day of the date, in YYYY-MM-DD format, in the timezone the date references.
So for example, localDay(new Date("2017-08-24T03:29:22.099Z"))
will return "2017-08-23"
even though it's already the 24th at UTC.
You'll need to polyfill Date.prototype.toISOString for it to work in Internet Explorer 8, but it should be supported everywhere else.