A lot of the JavaScript examples out there to get current date in the format yyyy-mm-dd (or dd/mm/yyyy, etc) don’t highlight the fact that they make assumptions about whether they return date as the user’s local time or UTC time. This is clearly important!

UTC Time

UTC time is elegantly solved by this one liner as “toISOString” gives us a yyyy-mm-dd date in the first 10 characters of it’s result string:

var d = new Date().toISOString().slice(0,10);

User’s Local Time

Local time requires a bit more effort as there is no return a date in the same format as “toISOString” but in the client’s local timezone. Instead we have to do this…

function DateToFormattedString(d) {         
        var yyyy = d.getFullYear().toString();                                    
        var mm = (d.getMonth()+1).toString(); // getMonth() is zero-based         
        var dd  = d.getDate().toString();             
        return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);

If you’re doing anything heavier than this with dates in JavaScript (particularly timezone / daylight savings conversions, you’re gonna want to check out the Moment.js library which fills in the gaps in JavaScripts woefully inadequate date handling.