alert(dateObj)
gives Wed Dec 30 2009 00:00:00 GMT+0800
How to get date in format 2009/12/30
?
With the accepted answer, January 1st would be displayed like this: 2017/1/1
.
If you prefer 2017/01/01
, you can use:
var dt = new Date();
var date = dt.getFullYear() + '/' + (((dt.getMonth() + 1) < 10) ? '0' : '') + (dt.getMonth() + 1) + '/' + ((dt.getDate() < 10) ? '0' : '') + dt.getDate();
ES2018 introduced regex capture groups which you can use to catch day, month and year:
const REGEX = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2});
const results = REGEX.exec('2018-07-12');
console.log(results.groups.year);
console.log(results.groups.month);
console.log(results.groups.day);
Advantage of this approach is possiblity to catch day, month, year for non-standard string date formats.
Ref. https://www.freecodecamp.org/news/es9-javascripts-state-of-art-in-2018-9a350643f29c/
Why not using the method toISOString()
with slice
or simply toLocaleDateString()?
Check here:
const d = new Date(); // today, now
console.log(d.toISOString().slice(0, 10)) // YYYY-MM-DD
console.log(d.toLocaleDateString('en-US')); // M/D/YYYY
console.log(d.toLocaleDateString('de-DE')); // D.M.YYYY
console.log(d.toLocaleDateString('pt-PT')); // DD/MM/YYYY
Here is a cleaner way getting Year/Month/Day with template literals:
var date = new Date();
var formattedDate = `${date.getFullYear()}/${(date.getMonth() + 1)}/${date.getDate()}`;
console.log(formattedDate);
You can simply use This one line code to get date in year-month-date format
var date = new Date().getFullYear() + "-" + new Date().getMonth() + 1 + "-" + new Date().getDate();
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
newdate = year + "/" + month + "/" + day;
or you can set new date and give the above values