FAQ Topic - How can I create a Date from a String? (2009-10-05)

F

FAQ server

-----------------------------------------------------------------------
FAQ Topic - How can I create a Date from a String?
-----------------------------------------------------------------------

An Extended ISO 8601 local Date format ` YYYY-MM-DD ` can be parsed to a
Date with the following:-

/**Parses string formatted as YYYY-MM-DD to a Date object.
* If the supplied string does not match the format, an
* invalid Date (value NaN) is returned.
* @param {string} dateStringInRange format YYYY-MM-DD, with year in
* range of 0000-9999, inclusive.
* @return {Date} Date object representing the string.
*/
function parseISO8601(dateStringInRange) {
var isoExp = /^\s*([\d]{4})-(\d\d)-(\d\d)\s*$/,
date = new Date(NaN), month,
parts = isoExp.exec(dateStringInRange);

if(parts) {
month = +parts[2];
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
} else {
date.setHours(0, 0, 0, 0);
}
}
return date;
}


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

Dr J R Stockton

In comp.lang.javascript message <[email protected]
, Sun, 4 Oct 2009 23:00:03, FAQ server <[email protected]> posted:

FAQ Topic - How can I create a Date from a String?

That makes no sense; should be "Date Object". And the string is not
*used* to *make* the Object; the date which the string represents
defines the value of the Object.

FAQ Topic - How can I obtain a Date Object with value set by a String?

An Extended ISO 8601 local Date format ` YYYY-MM-DD ` can be parsed to a
Date with the following:-

No; the format YYYY-MM-DD does not represent any date.

A Date Object representing the content of a string in Extended ISO 8601
local Date format ` YYYY-MM-DD ` can be obtained using the following:-

/**Parses string formatted as YYYY-MM-DD to a Date object.
* If the supplied string does not match the format, an
* invalid Date (value NaN) is returned.
* @param {string} dateStringInRange format YYYY-MM-DD, with year in
* range of 0000-9999, inclusive.
* @return {Date} Date object representing the string.
*/
function parseISO8601(dateStringInRange) {
var isoExp = /^\s*([\d]{4})-(\d\d)-(\d\d)\s*$/,

Do the square brackets serve any useful purpose?
date = new Date(NaN), month,
parts = isoExp.exec(dateStringInRange);

if(parts) {
month = +parts[2];
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
} else {
date.setHours(0, 0, 0, 0);

That setHours should not be necessary; and the ECMA standard should make
it so.

I'd slightly prefer, while setHours is present, to use
if ( == ) rather than if ( != ) .


date.setFullYear(parts[1], --month, parts[3]);
if ( month != date.getMonth() ) { // seems clearer
 
D

Dr J R Stockton

In comp.lang.javascript message <[email protected]
8924D9443D28E23ED5CD>, Tue, 6 Oct 2009 18:03:38, John G Harris
<snip>

Strictly speaking, the Date Object is the object named Date : the
constructor you use when you do new Date().

The term is good enough for ISO/IEC 16262 15.9, which (for example)
includes "A Date object contains a number indicating a particular
instant in time to within a millisecond. The number may also
be NaN, indicating that the Date object does not represent a specific
instant of time.".

If you were quibbling over capitalisation, you should have done so
explicitly. Our Editor should be able to handle such details.
 
J

John G Harris

In comp.lang.javascript message <[email protected]
8924D9443D28E23ED5CD>, Tue, 6 Oct 2009 18:03:38, John G Harris
<[email protected]> posted:


The term is good enough for ISO/IEC 16262 15.9, which (for example)
includes "A Date object contains a number indicating a particular
instant in time to within a millisecond.
<snip>

In any other OO language you would say that Date is the function object
and a Date instance is an object constructed by Date. 'instance' should
be used more often in javascript discussions.

In the standard, "Date object" means the function object in section 4.2
and an object constructed by Date in section 15.9. The term is
thoroughly ambiguous and should be avoided where clarity is desired.

John
 
T

Thomas 'PointedEars' Lahn

John said:
<snip>

In any other OO language you would say that Date is the function object
and a Date instance is an object constructed by Date.

It is also used in the ECMAScript Language Specification(s) on numerous
occasions.
'instance' should be used more often in javascript discussions.

My words exactly.


PointedEars
 
D

Dr J R Stockton

In comp.lang.javascript message <lghpc5dq02b5vs17m33dn6vlo85vjpq8rt@4ax.
com>, Wed, 7 Oct 2009 18:49:45, Hans-Georg Michna <hans-
(e-mail address removed)> posted:
While you're at it, I've seen scripts that compare two Date
objects directly, but I could not find any clue in any
specification that this should work.


To most people, I guess it's not obvious what D1 == D2 does; I believe
it compares the objects to see if they are the same object. One might
think it could compare the toString() results, but that would be
wasteful of effort. Just compare +D1 with +D2.

You could have read <URL:http://www.merlyn.demon.co.uk/js=-date0.htm#DC>
instead of asking.

The quoted text above also mentions the contained milliseconds,
but it does not say that the Date object behaves like a number.

I only quoted the part of the document relevant to previous discussion;
if you want to know more, you should read it.
It does not say how you get at those milliseconds. Elsewhere it
is specified that you can use .getTime() to get at them.

Or .valueOf() - and if you consider the whole document you will see that
a unary + operator should do it (it does, and unary - does, and D-0
works, as does multiplying or dividing by 1, or using Number(D) ).


AFAICS, a Date object is not required to store its value as an IEEE
Double; but it is required to behave as if that were the case (apart
from the speed of operations, which is unspecified). There might be
advantage in actually storing a 64-bit signed integer.
 
A

Asen Bozhilov

FAQ server" said:
function parseISO8601(dateStringInRange)

parseISO8601 and Date object in ECMA 3 works with dates from Gregorian
calendar. And they follows algorithm for leap year in Gregorian
calendar, where:

year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)

In Julian calendar leap year is every year who's:

year % 4 == 0

Gregorian calendar since from 24 February 1582.
<URL:http://en.wikipedia.org/wiki/Gregorian_calendar>

Because that, date likes this:

new Date(1300, 1, 29); // Mon Mar 01 1300 00:00:00 GMT+0200 (FLE
Standard Time)
new Date(1400, 1, 29); // Sat Mar 01 1400 00:00:00 GMT+0200 (FLE
Standard Time)
new Date(1500, 1, 29); // Thu Mar 01 1500 00:00:00 GMT+0200 (FLE
Standard Time)

For my that's dates is absolutely valid date. That's dates existed in
real life.
 
G

Garrett Smith

John said:
<snip>

Strictly speaking, the Date Object is the object named Date : the
constructor you use when you do new Date().

And one of those is "a Date".

A Date *is* and Object. Adding "Object" is redundant.
 
D

Dr J R Stockton

In comp.lang.javascript message <[email protected]
8924D9443D28E23ED5CD>, Wed, 7 Oct 2009 19:58:57, John G Harris
In the standard, "Date object" means the function object in section 4.2
and an object constructed by Date in section 15.9. The term is
thoroughly ambiguous and should be avoided where clarity is desired.

You'll tell that to TC39, I trust?
 
D

Dr J R Stockton

In comp.lang.javascript message <[email protected]
september.org>, Wed, 7 Oct 2009 14:59:03, Garrett Smith
And one of those is "a Date".

A Date *is* and Object. Adding "Object" is redundant.

YGCIB.

It is not superfluous, since "date" is an ordinary English word and may
also be used with that meaning - and in a natural language a little
redundancy is often a great help in transferring a meaning without
either error or doubt.
 
D

Dr J R Stockton

In comp.lang.javascript message <b097d82a-9ff2-48a9-9472-83ea7c86b793@r3
6g2000vbn.googlegroups.com>, Wed, 7 Oct 2009 12:48:08, Asen Bozhilov
parseISO8601 and Date object in ECMA 3 works with dates from Gregorian
calendar. And they follows algorithm for leap year in Gregorian
calendar, where:

year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)

In Julian calendar leap year is every year who's:

year % 4 == 0

Gregorian calendar since from 24 February 1582.
<URL:http://en.wikipedia.org/wiki/Gregorian_calendar>

Because that, date likes this:

new Date(1300, 1, 29); // Mon Mar 01 1300 00:00:00 GMT+0200 (FLE
Standard Time)
new Date(1400, 1, 29); // Sat Mar 01 1400 00:00:00 GMT+0200 (FLE
Standard Time)
new Date(1500, 1, 29); // Thu Mar 01 1500 00:00:00 GMT+0200 (FLE
Standard Time)

For my that's dates is absolutely valid date. That's dates existed in
real life.

ECMA 262 Edn 3 and ISO/IEC 16262 specify that the calendar to be used
for all dates is the extrapolated Gregorian calendar (with the Summer
Time rules of the machine's locality and the present time[*]). ECMA 262
Final Draft 5 agreed.

For Julian Calendar date routines in JavaScript, see in
<URL:http://www.merlyn.demon.co.uk/js-date8.htm>.

Accommodating all changes of Summer Time rules and Calendar rules would
be difficult, error-prone, and not worth while. Note, for example, that
in Great Britain and elsewhere the UTC instants represented by those
"new Date" calls would actually have been in 1299 1399 1499, since the
legal supputation of the year changed the number at March 25th.

Then consider Alaska, which in October 1867 had two consecutive Fridays,
October 6th and 18th?

And should the date of the Papal Bull /Inter gravissimas/ be given as
(in Italian) 24th February 1581 (Julian, O.S.) or as 6th March 1582
proleptic Gregorian or as in "Datum Tusculi Anno Incarnationis Dominicae
M. D. LXXXI. Sexto Calend. Martij, Pontificatus nostri Anno Decimo.",
which is what His Holiness apparently signed?


[*] Which means that all law-abiding America-resident JavaScript users
should have updated their systems (or have had Vista, etc., do it for
them) at exactly 12:00 a.m. on 03/01/2007, since that is by US Law when
their new rules actually became current.
 
D

Dr J R Stockton

In comp.lang.javascript message <vu5rc5563vrjdrifr9voh68jgf7fevn6co@4ax.
com>, Thu, 8 Oct 2009 09:54:56, Hans-Georg Michna <hans-
(e-mail address removed)> posted:
Could you check the link? I get Page not found (404). Perhaps a
little typo.

However, even if that page explains very well how Date behaves,
it is still not an official specification, or is it? I mean, who
guarantees that Date will still behave that way in the next new
browser or browser version?

The newsgroup FAQ and <URL:http://www.merlyn.demon.co.uk/js-dates.htm>
have links to the current and draft future standards. They define how
browsers (etc.) ought to behave.

There is IMHO no likelihood that the long-established general properties
of Date will be changed in the Standard; but other properties will,
should, and may be added.

Page <URL:http://www.merlyn.demon.co.uk/js-datex.htm> shows a number of
bugs which ought to be removed from future versions of browsers.
 
G

Garrett Smith

Dr said:
In comp.lang.javascript message <[email protected]
september.org>, Wed, 7 Oct 2009 14:59:03, Garrett Smith
[...]
And one of those is "a Date".

A Date *is* and Object. Adding "Object" is redundant.
correction: A Date *is* an Object.
It is not superfluous, since "date" is an ordinary English word and may
also be used with that meaning - and in a natural language a little
redundancy is often a great help in transferring a meaning without
either error or doubt.
In context of a javascript FAQ, capitalized "Date" seems obvious to me.
Are there others who feel it is confusing?
 
R

Richard Cornford

Sorry, in this case it would, of course, be the documentation
of the JavaScript implementation or perhaps any general
specification of the language.

No, in this case it is the language specification. There is no reason
for looking at implementation documentation unless the subject of
interest is a language extension that is present in that
implementation (and you still need ECMA 262 in order to know what is
or is not an extension), or an ECMAScript implementation bug. Language
extensions tend to get in the way of cross-browser scripting, and
implementation bugs don't tent to be usefully (or meaningfully)
documented, so there is really very little reason for being interested
in implementation documentation at all.

Richard.
 
D

Dr J R Stockton

In comp.lang.javascript message <kjosc512pir1hatjch6i65oeg3pudbbeuh@4ax.
com>, Fri, 9 Oct 2009 00:34:58, Hans-Georg Michna <hans-
(e-mail address removed)> posted:
thanks. I understand all that. I just cannot find it in any
official specification.

Then you should read newsgroup FAQ section 2.1.
If there is any place in the official documentation, like the
Gecko DOM docs,

Those are implementation specifications, and not for JavaScript. Would
you go to an S-Bahn station hoping to see the Pope at home there?

But it is well possible that I have overlooked the relevant
documentation or severely misunderstood it. On the other hand,
if I misunderstand it, then some others will also misunderstand
it.

It is in the nature of a Formal Standard that it is unavoidably hard to
understand. Especially by those who have not read it.

If you have visited any JavaScript portion of my Web site, you will have
had an opportunity of seeing a link to the section's index page (as in
the sig below); and that includes links to the formal JavaScript
standards.

Googling for JavaScript Standard provides clues, as does
<http://en.wikipedia.org/wiki/JavaScript>.
 
D

Dr J R Stockton

In comp.lang.javascript message <9d6vc5ltiomn415vksacd9ivk13999epfh@4ax.
com>, Fri, 9 Oct 2009 22:43:17, Hans-Georg Michna <hans-
(e-mail address removed)> posted:
Yes, I see your point. I take it that that is the normative
documentation.

Only in practice.

It is outranked by ISO/IEC 16262, which is a later version of
substantially the same document (and IMHO more readable). No technical
change was intended between the documents.

One major browser maker, however, has evident difficulty in correctly
implementing at least one International Standard. Coders should not
rely on equal compliance in all browsers.
 
G

Garrett Smith

Garrett said:
Dr said:
In comp.lang.javascript message <[email protected]
september.org>, Wed, 7 Oct 2009 14:59:03, Garrett Smith
John G Harris wrote:
On Mon, 5 Oct 2009 at 19:43:47, in comp.lang.javascript, Dr J R
Stockton
wrote:
In comp.lang.javascript message
<[email protected]
, Sun, 4 Oct 2009 23:00:03, FAQ server <[email protected]>
posted:
[...]
Strictly speaking, the Date Object is the object named Date : the
constructor you use when you do new Date().

And one of those is "a Date".

A Date *is* and Object. Adding "Object" is redundant.
correction: A Date *is* an Object.
It is not superfluous, since "date" is an ordinary English word and may
also be used with that meaning - and in a natural language a little
redundancy is often a great help in transferring a meaning without
either error or doubt.
In context of a javascript FAQ, capitalized "Date" seems obvious to me.
Are there others who feel it is confusing?


How does this look?

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

Garrett Smith

Johannes said:
Garrett Smith :


Excellent, as far as I can see, with just one possible problem : year
zero, which is admissible in some contexts but not, e.g., in XQuery.

Unless there are reasons to believe users will actually know what it means
and require its use, I suggest replacing "year >= 0" with "year > 0".

Who is the user? The person copy-pasting "formatDate" or the end user
who is interacting with the browser?

Regardless, the year 0 issue has been discussed here previously.

ISO 8601 explicitly lists year 0000.

| Calendar years are numbered in ascending order according to the
| Gregorian calendar by values in the range [0000] to [9999].

ISO 8601 is linke from that FAQ Entry:
http://jibbering.com/faq/#formatDate
 
G

Garrett Smith

Hans-Georg Michna said:
Very true, but year zero should be admissible in no context,
because it never existed. There is no year zero.

There is in ISO 8601. Again, please do read the FAQ.
http://jibbering.com/faq/#formatDate

Year 0 is used in natural sciences (astronomy, archeology, paleontology,
etc). 1 BC or 1 BCE is a PITA to deal with.

ISO 8601 is the relevant specification here.

This has been discussed here at length, within the last 6 months.
 

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