I have a date with the format Sun May 11,2014
. How can I convert it to 2014-05-11
using JavaScript?
This worked for me to get the current date in the desired format (YYYYMMDD HH:MM:SS):
var d = new Date();
var date1 = d.getFullYear() + '' +
((d.getMonth()+1) < 10 ? "0" + (d.getMonth() + 1) : (d.getMonth() + 1)) +
'' +
(d.getDate() < 10 ? "0" + d.getDate() : d.getDate());
var time1 = (d.getHours() < 10 ? "0" + d.getHours() : d.getHours()) +
':' +
(d.getMinutes() < 10 ? "0" + d.getMinutes() : d.getMinutes()) +
':' +
(d.getSeconds() < 10 ? "0" + d.getSeconds() : d.getSeconds());
print(date1+' '+time1);
The simplest way to convert your date to the yyyy-mm-dd format, is to do this:
var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
.toISOString()
.split("T")[0];
How it works:
new Date("Sun May 11,2014")
converts the string "Sun May 11,2014"
to a date object that represents the time Sun May 11 2014 00:00:00
in a timezone based on current locale (host system settings)new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
converts your date to a date object that corresponds with the time Sun May 11 2014 00:00:00
in UTC (standard time) by subtracting the time zone offset.toISOString()
converts the date object to an ISO 8601 string 2014-05-11T00:00:00.000Z
.split("T")
splits the string to array ["2014-05-11", "00:00:00.000Z"]
[0]
takes the first element of that arrayvar date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
.toISOString()
.split("T")[0];
console.log(dateString);
A combination of some of the answers:
var d = new Date(date);
date = [
d.getFullYear(),
('0' + (d.getMonth() + 1)).slice(-2),
('0' + d.getDate()).slice(-2)
].join('-');
If you don't have anything against using libraries, you could just use the Moments.js library like so:
var now = new Date();
var dateString = moment(now).format('YYYY-MM-DD');
var dateStringWithTime = moment(now).format('YYYY-MM-DD HH:mm:ss');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
new Date(new Date(YOUR_DATE.toISOString()).getTime() -
(YOUR_DATE.getTimezoneOffset() * 60 * 1000)).toISOString().substr(0, 10)
new Date().toLocaleDateString('pt-br').split( '/' ).reverse( ).join( '-' );
or
new Date().toISOString().split('T')[0]
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString()
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString().split('T')[0]
Try this!