How do I format a Date object with javascript?

A local Date object where 0 <= year <= 9999 can be formatted to a common ISO 8601 format YYYY-MM-DD with:-

 /** Formats a Date to YYYY-MM-DD (local time), compatible with both 
 *  ISO 8601 and ISO/IEC 9075-2:2003 (E) (SQL 'date' type). 
 *  @param {Date} dateInRange year 0000 to 9999. 
 *  @throws {RangeError} if the year is not in range 
 */ 
 function formatDate(dateInRange) { 
   var year = dateInRange.getFullYear(), 
     isInRange = year >= 0 && year <= 9999, yyyy, mm, dd; 
   if(!isInRange) { 
     throw RangeError("formatDate: year must be 0000-9999"); 
   } 
   yyyy = ("000" + year).slice(-4); 
   mm = ("0" + (dateInRange.getMonth() + 1)).slice(-2); 
   dd = ("0" + (dateInRange.getDate())).slice(-2); 
   return yyyy + "-" + mm + "-" + dd; 
 } 


Other FAQ Resources: