Skip to content
barbir edited this page Sep 28, 2010 · 5 revisions

Javascript Date Format Patch 0.9.9

About

In lack of decent formatting ability of Javascript Date object, I have created this "patch" for the Date object which will add the following functions:

  • Date.format(dateObject, format)
  • dateObject.toFormattedString(format)
  • Date.parseFormatted(value, format)
  • dateObject.fromFormattedString(value, format)

Both of these will allow you to convert dates to strings in your desired format.

Licence

Copyright (c) 2010 Miljenko Barbir

Dual licensed under the MIT and GPL licenses.

Usage

You can use the format method as a static function to which you need to provide two parameters: date object and the format definition.

var d = new Date(2001, 1, 3, 4, 5, 6, 7);
Date.format(d, 'dd.MM.yyyy. HH:mm:ss.zzz');	// "03.02.2001. 04:05:06.007"

You can use the format method as a member function of the Date object instance to which you need to only the format parameter.

var d = new Date(2001, 1, 3, 4, 5, 6, 7);
d.toFormattedString('yyyy-MM-dd');	        // "2001-02-03"

You can use the parse method as a static function to which you need to provide two parameters: date string and the format definition.

var d = new Date();
d = Date.parseFormatted('03.02.2001. 04:05:06.007', 'dd.MM.yyyy. HH:mm:ss.zzz');

You can use the parse method as a member function of the Date object instance to which you need to provide two parameters: date string and the format definition.

var d = new Date();
d.fromFormattedString('2001-02-03', 'yyyy-MM-dd');
Clone this wiki locally