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

F

FAQ server

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

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


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

Asen Bozhilov

Another possible approach is:

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 = year + 10000;
mm = (dateInRange.getMonth() + 1) + 100;
dd = dateInRange.getDate() + 100;
return (yyyy + "-" + mm + "-" + dd).replace(/\b1/g, '');
}
 
D

dhtml

Another possible approach is:

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 = year + 10000;
mm = (dateInRange.getMonth() + 1) + 100;
dd = dateInRange.getDate() + 100;
return (yyyy + "-" + mm + "-" + dd).replace(/\b1/g, '');

It's fine, but why do you think this is better or do you think the FAQ
should use this instead?

I've not been posting because my primary machine is down and don't
have newsreader setup on this machine. I do not like GG and I think I
may have just posted "c" by accident.

I am aware of the FAQ entry for "how do I format a number" and the
proposal on how to read and post (using a newsreader). I will get to
those. Plus the JSON stuff, which takes a bit more time.

Should be on it by Thursday.
 
A

Asen Bozhilov

dhtml said:
It's fine, but why do you think this is better or do you think the FAQ
should use this instead?

Both versions are good. I posted my code, just for give another
alternative for people who read the FAQ entries. I am not pretended
for my version is better than FAQ code. In my version I do not use
three time string concatenations plus three invocation of `slice'
method. I am just using mathematical operation plus `replace' which I
suppose is faster than than version used by FAQ.
 
L

Lasse Reichstein Nielsen

I think RegExp replace is a little heavy-duty for something like this.
How about
return String(yyyy).substring(1) + "-" +
String(mm).substring(1) + "-" +
String(dd).substring(1);
?

/L
 
D

Dr J R Stockton

In comp.lang.javascript message <0df43f3b-dfc9-41a7-9e42-bf85f31ff2f6@t2
0g2000yqa.googlegroups.com>, Tue, 3 Aug 2010 02:00:48, Asen Bozhilov
I am just using mathematical operation plus `replace' which I
suppose is faster than than version used by FAQ.


You can easily test that using a * * COPY * * of
<URL:http://www.merlyn.demon.co.uk/js-quick.htm>. 'Press' Demo 6 times,
edit in your functions and their calls, press Eval. Repeat increasing
K_ and pressing Eval until you get reasonable times below the buttons.

In Firefox 3.0.19, WinXP sp3 P4/3GHz, K_ = 15000, I get 0,11,140,276
and similar - the FAQ is a little over twice as fast. Chrome 5.0,
0,10,34,59. Safari 5.0, 0,1,37,59. Opera 10.10, 0,0,140,422. But IE8,
0,0,344,297 - perhaps MS are comparatively good at RegExps.

The FAQ does need good, realistic examples of RegExps, though.
 
A

Asen Bozhilov

Lasse said:
I think RegExp replace is a little heavy-duty for something like this.

Indeed. I had to test in various implementations. I tested my approach
in Rhino 1.7 under Debian 5.0 and was faster than FAQ. From tests
provided by Dr J R Stockton and mines FAQ approach is faster than my.
Do you have explanation why? I am still thinking RegExp approach
should be faster than three string concatenation + three invocations
of `slice'.
How about
 return String(yyyy).substring(1) + "-" +
     String(mm).substring(1) + "-" +
     String(dd).substring(1);
?

Btw, I used similar version before I post RegExp approach. Do you have
any reasons to use `substring' instead of `slice'?
 
D

Dr J R Stockton

Wed said:
I think RegExp replace is a little heavy-duty for something like this.
How about
return String(yyyy).substring(1) + "-" +
String(mm).substring(1) + "-" +
String(dd).substring(1);
?

One should not expect the date formatter to be called in isolation. The
proper way must IMHO be to have a rather general padding function or a
set of moderately general ones, such as

function LZ(n) { return (n!=null&&n<10&&n>=0?"0":"") + n }

function SpcsTo(S, L) { S += ""
while (S.length<L) S = " " + S ; return S }

function ZeroTo(S, L) { S += ""
while (S.length<L) S = "0" + S ; return S }

function ToNd(X, N) { // developed from ZeroTo
if (X<0) return "-" + ToNd(-X, N)
X += "" ; while (X.length<N) X = "0" + X ; return X }

function ChrsTo(S, L, C) {
for (var i = String(S).length ; i < L ; i++) S = C + S
return S }

function TailTo(X, Ch, L) { var S = String(X)
while (S.length < L) S += Ch
return S }

(or, if preferred, Methods of Number) and then to write something like

return ZeroTo(yyyy, 4) + "-" + LZ(mm) + "-" + LZ(dd)

Note that LZ gives an appropriate result for any possible value of n
including NaN (except for those who want to see '-0').

Now there is for example an obvious way (for almost all continents) of
formatting time with LZ; and formatting ww in standard Week Numbers, and
ddd in Ordinal Dates and integer degrees or grads (though I also have a
LZZ for that),
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top