In comp.lang.javascript message <
[email protected]
september.org>, Fri, 12 Jun 2009 01:14:07, Garrett Smith
The entry:
"11.1 How do I get my browser to report javascript errors?"
covers the subject of browsers reporting errors.
But it says nothing about the effect of calling throw.
I do not know KDF9, but "throw" is a basic computer science term nowadays.
Of course; but there are still two different types of throw call in the
Standard; the reserved word, and the action internal to failing
routines. a (CtrlF-type) search cannot distinguish. If the reserved
word had been thro, raise, abort, etc., the clash would not have
occurred. It's like the difficulty in talking about undefined results
in a context where "undefined" can mean an Object type, the value of an
object of that type, or its literal representation in code.
No! The alert method has no place in such code. Calling alert there
would be a bad side effect. It would be awkward for the caller to
handle that gracefully. Consider:-
var realAlert = window.alert;
window.alert = logError;
formatDate( myDate );
window.alert = realAlert;
That is awful.
Anyone who redefines something provided by the system must look to see
whether that object is used elsewhere in the code.
Anyone taking code from a FAQ should read it first, and should test it
before embedding it deeply in other code. Writing alert(string) is a
concise and reliable way both of indicating a problem on initial test
and showing where other error handling might be substituted. Just
quitting is not satisfactory. Returning a string such as "Year error"
instead of a YYYY-MM-DD string also works; it will be noticed.
In production code, the error should never be allowed to occur.
The return value of Date.prototype.toString itself is implementation-
dependent and that is stated in the specification which is linked.
It is, for non-NAN objects, always a readable representation of the
date; the result for NaN varies more than that.
You are not remembering what a FAQ for a general language newsgroup
should be like. You presume too much knowledge of the language. The
FAQ should be aimed at the needs of those who wander in from time to
time with a serious but ill-expressed question and are promptly driven
out again by the Great Bully.
It's like a "Null Object".
It must not be called that, though.
Taking all of the suggestions, the new draft follows:-
================================================================
4.1 How do I write and read a date with javascript?
The ISO 8601 Extended format can be understood internationally, without
xxx ^An (there are more than one) (don't use Any[0])
world-wide ---> xxxxxxxxxxxxxx
ISO 8601 Extended formats can be...
No; that definitely implies that all of them can be.
or
[Most|Common|Many] 8601 Extended formats can be...
or even
Many common ISO 8601 Extended formats can be..
Obvious minor variations such as year outside 0000-9999 and the presence
of time fields apart, there are not enough extended formats to justify
"Many".
Look at the return statement:-
| return yyyy + "-" + mm + "-" + dd;
The intent of the code and code is doing could not be any clearer.
Yes, but that would still apply if year & yyyy were replaced by Y, mm by
M, dd by D. The comment must say that the output is YYYY-MM-DD, which
makes all else obvious.
Don't those two words mean the same thing?
No. A suffix is below, an index or superfix above - as in HTML <sub>
<sup>. A prefix is before, a postfix is after, both on-the-line.
Suffix in this context will be understood, but postfix is correct.
By what, a user-defined one? That would break it.
Not if it had all the necessary methods etc., just with changes
elsewhere. "Native" is not needed, and not guaranteed.
if(parts) {
date.setFullYear(parts[1], parts[2] - 1, parts[3]);
date.setHours(0,0,0,0);
With new Date(NaN), setFullYear cannot avoid setting the "local time
part"; therefore, setHours may not now be essential.
Good.
I only wrote "may not be".
The RegExp is not acceptable. It partly but incompletely validates
the
date. The date should be either tested for character pattern or not so
tested; and it should either be fully numerically validated or not
numerically validated at all.
Again, the answers are all in the archives[1], and Thomas seems to
be
slipping since AFAIR he has not told you that.
Test the pattern for, at the very minimum,
/^\D*\d+\D+\d+\D+\d{1,2} then non-digit or end/.
Apply the three fields as above into new Date,
check the Month of the date object agrees with the second numeric field.
It occurred to me to validate that by calling the relevant date methods
but I did not attach much significance to it and considered the
function could return an adjusted date (from MakeDay), should the
caller pass a February 29 on a non-leap year, for example.
It is abominable to do that for one breach of Gregorian notation but not
for others. Month=13 is just as valid as February 31st.
In fact, there should be two versions of the read routine; one for when
the string is guaranteed in field order and Y M D being good (there is
no need to require a specific separator or number of digits), and one
which validates the numbers. There is no necessary need to validate the
pattern or punctuation to a greater extent than the rest of the code
needs.
If validation is the way to go, the parts should be checked in order
from most to least likely to fail. That is the days, then months, then
years. By doing this, failure is reached faster.
No. Most inputs will pass validation, so the need is to reach success
fastest. That's not necessarily the same thing. Also, since dates
needing validation will generally be form entries, speed is not
important at modern clock rates.
If the validation is going to fail, it will have a greater chance of
failing sooner with a stricter regexp (a null match avoids method
calls):
/^\s*([\d]{4})-(0[1-9]|1[0-2])-([0-2][0-9]|(?:3[0|1]))\s*$/
But that passes Feb 31, which gives a date of Mar 2 or 3. And a long
RegExp is slower in operation.
We went into validation rather thoroughly before. Read the archives.
However, the simpler pattern posted earlier is easier to read and
perhaps more suitable for the FAQ.
The pattern should ignore leading and trailing whitespace only and not
try and find a date format buried in a string. \s is probably enough
here. I know that implementations are not consistent with each other or
the specification on \s and we have discussed the Mongolian vowel
separator and no-break space (\u00a0).
I wrote, legibly enough, "at the very minimum", in order to show only
what was needed for validation by checking getMonth to work. But why
not use \D, which correctly accepts ALL whitespace varieties and permits
finding dates in strings containing other non-digits? The purpose is to
validate the date indicated, not the ISO compliance.
Revised:-
/**Parses string formatted as YYYY-MM-DD to a Date object.
^a xxxxxxxxxxxx superfluous
* If the supplied string does not match the format, an xxxxxxxx superfluous
* invalid Date (value NaN) is returned.
* @param {string} dateStringInRange format YYYY-MM-DD, with year in
No need to specify the format twice, especially in a language delivered
as source.
* range of 0000-9999, inclusive.
* @return {Date} Native Date object representing the string.
*/
function parseISO8601( dateStringInRange ) {
Following your earlier argument, the function name should indicate which
ISO format type. InRange is superfluous.
var date = new Date(NaN),
isoExp, parts;
isoExp = /^\s*([\d]{4})-(\d\d)-(\d\d)\s*$/;
No general need to check field lengths, except for not exceeding DD.
parts = isoExp.exec(dateStringInRange);
if(parts) {
date.setFullYear(parts[1], parts[2] - 1, parts[3], 0, 0, 0, 0);
It seems unwise to use arguments that ECMA 3 & FD 5 specify are not
there. The length of setFullYear is 3 -
new Date().setFullYear.length gives 3.
if(parts[2] != date.getDate()
|| parts[1] != date.getMonth() + 1
|| parts[0] != date.getFullYear() ) {
You clearly have not understood. All this is in the archives, and on my
site. There is no need to test getDate, since if the value given is
outside the month but in 00-99 (guaranteed by RegExp) then the getMonth
test must fail. There is no need to test the Year either, since
setFullYear does not add 1900 to years under 100.
setTime() seems nicer, since it only ever stuffs its clipped numeric
argument in the Object, whereas setFullYear() can do more. And it's
easier to see from the standard what an argument of NaN must do.
}
}
return date;
}
And more liberal than the one I provided.
As explained.
It looks like Date2[2] handles parsing and setting of various ISO 8601
formats.
AFAIR, not "various"; it handles all of the date and date/time formats,
but not the interval or duration ones.
I think is more complicated than the example would need. While you have
some good ideas, I find function names like ZBDoCY to be unmemorable
and confusing.
Zero-Based Day of Calendar Year; in other words, Ordinal Date minus one.
But that's within a routine, not part of the user interface. It's only
ever assigned near the end of a routine and only ever used in the next
statement, followed by a return that does not use it.
Google finds it, but not Google Maps; so it won't get confused with a
place in Eastern Europe.
Note also that Date2 is a proposal for implementation as a new native
Object, so the JavaScript would then be converted to compiled code in,
possibly, C++.
[0] Unwise to claim that ISO Week Numbering will be understood in NA.
What is NA?
Context-dependent; Namibia, or North America (give or take Mexico and
the 20 others). Wikipedia knows it. Often, rightly or wrongly, used
for US+CA.
Inadequately written : the page implies that YYYY-MM-DD is the only ISO
date format. Ignoring extensions and truncations and compressions,
there are two others. It links to <
http://www.w3.org/International/ques
tions/qa-date-format> which is also unworthy : it says "The format
MM/DD/YY is unique to the United States." which alas is not true. I
suspect it's common in the Northern Sidekick, and likely to be used in
places that don't natively use English.