FAQ Topic - How do I format a Date object with javascript? (2010-01-27)

  • Follow


-----------------------------------------------------------------------
FAQ Topic - 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;
}

http://www.merlyn.demon.co.uk/js-date9.htm


The complete comp.lang.javascript FAQ is at 
http://jibbering.com/faq/

-- 
 
The sendings of these daily posts are proficiently hosted 
by http://www.pair.com.

0
Reply javascript4 (1176) 1/27/2010 12:00:03 AM


0 Replies
1699 Views

(page loaded in 0.026 seconds)

Similiar Articles:









7/24/2012 9:10:27 AM


Reply: