FAQ Topic - How can I create a Date object from a String? (2011-02-15)

F

FAQ server

-----------------------------------------------------------------------
FAQ Topic - How can I create a Date object 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);
}
}
return date;
}


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

Evertjan.

FAQ server wrote on 15 feb 2011 in comp.lang.javascript:
-----------------------------------------------------------------------
FAQ Topic - How can I create a Date object 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.

What is all this '@' stuff, just to scare the newbees off?

[Scaring newbees of in itself might be a laudable passtime,
but not in the FAQ please]
*/
function parseISO8601(dateStringInRange) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,

What nonsense not to allow a
single month or day character, yyyy-[m]m-[d]d,
and allow for external white space.

Is external whitespace really part of ISO 8601?

Must the Q "How can I create a Date object from a String?"
realy be answered by a strict following of Extended ISO 8601?
date = new Date(NaN), month,
parts = isoExp.exec(dateStringInRange);

if(parts) {
month = +parts[2];

The + is not necessary as both following uses do automagic conversion.
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
}

Why not '};' ?
}
return date;
}

I suggest to forget about the rules of ISO 8601,
but to concentrate on it's usefull international acceptance
of the sequence order.

to allow:
yyyy-[m]m-[d]d
yyyy/[m]m/[d]d
yyyy.[m]m.[d]d
yyyymmdd
and not allow external whitespace.

=============================================
function parseYyyymmdd(dateString) {
var date = new Date(NaN);
dateString = dateString.replace(/(\d{4})(\d{2})(\d{2})/,'$1-$2-$3')
var parts = dateString.split(/[-/.]/);

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

John G Harris

FAQ server wrote on 15 feb 2011 in comp.lang.javascript:

I suggest to forget about the rules of ISO 8601,
but to concentrate on it's usefull international acceptance
of the sequence order.

to allow:
yyyy-[m]m-[d]d
yyyy/[m]m/[d]d
yyyy.[m]m.[d]d
yyyymmdd
and not allow external whitespace.
<snip>

Alternatively, add a note that there are too many date formats to cover
them all, but the above example should help you write code to meet your
own requirements.

John
 
E

Evertjan.

Jake Jarvis wrote on 15 feb 2011 in comp.lang.javascript:
<snip>

Why '};' ?

If all statements should end with a ';',
even though present parsers sometimes overlook the omission,
there is no reason to make an exception after '}'.

The FAQ should be conservative in this.
 
L

Lasse Reichstein Nielsen

Evertjan. said:
Jake Jarvis wrote on 15 feb 2011 in comp.lang.javascript:


If all statements should end with a ';',

They shouldn't.
even though present parsers sometimes overlook the omission,

That's "automatic semicolon insertion". It's part of the specification,
not just something the parsers have dreamed up. It allows you to omit
the semicolon in some of the cases where the syntax would otherwise
require it.
there is no reason to make an exception after '}'.

But the premise was wrong (that all statements should end with a
semicolon), so the conclusion is inconclusive.

The grammar specifies a semicolon as terminating any of: empty
statement,expression-statement, do-while statement, return, throw,
break or continue statements, or variable declarations.

The remaining statement types require, and allow, no semicolon, e.g.,
if, for, while, switch, try/catch/finally, statement block,
The FAQ should be conservative in this.

I agree that the FAQ should not omit any semicolons due to automatic
semicolon insertion.
On the other hand, it shouldn't add any spurious empty statements,
which is what adding a ';' after a '}' amounts to.

/L
 
E

Evertjan.

Lasse Reichstein Nielsen wrote on 15 feb 2011 in comp.lang.javascript:
They shouldn't.


That's "automatic semicolon insertion".

What is? The overlooking?

If I insert a colon, that is not automatic insertion, but manual
insertion, unless I am switched to an automatic mode.

I like either total ; insertion or minimal ; insertion, not a mixture.

To my eyes any other form looks dirty.
It's part of the specification,
not just something the parsers have dreamed up. It allows you to omit
the semicolon in some of the cases where the syntax would otherwise
require it.

As I said, that looks dirty.

It is the same as omitting indentation, perhaps in the relaistic but
inconsequential believe that indentation only slows down parsing.
But the premise was wrong (that all statements should end with a
semicolon), so the conclusion is inconclusive.

Read "should" like "should" in "examples in the faq should have proper
indentation.
The grammar specifies a semicolon as terminating any of: empty
statement,expression-statement, do-while statement, return, throw,
break or continue statements, or variable declarations.
The remaining statement types require, and allow, no semicolon, e.g.,
if, for, while, switch, try/catch/finally, statement block,

I do not foolow your reasoning.

I think any statement allows a ; at the end.

Perhaps our definition of "statement" differs?
I agree that the FAQ should not omit any semicolons due to automatic
semicolon insertion.

So it is true: "any statement should end with a ;"
On the other hand, it shouldn't add any spurious empty statements,
which is what adding a ';' after a '}' amounts to.

Perhaps a parser could read that as a spurious statement, like
indentation certainly is spurious to a parser, but the parser should be
wise enough to be "optimizing" and not to spend cycles in the execution
fase on this. After all present day interpreters are realy realtime
compilars and not linear interpreters of the source text file like the
primeaval version of the MSDOS batch interpreter, that couldn't even
"goto" a linearly previous label.

So I keep my "all statements should end with a ; in examples in the FAQ"
standing.
 
L

Lasse Reichstein Nielsen

Evertjan. said:
Lasse Reichstein Nielsen wrote on 15 feb 2011 in comp.lang.javascript:


What is? The overlooking?

What you call "overlooking", yes. You are allowed to omit some
semicolons from ECMAScript programs where they are otherwise
used to terminate a statement.
If I insert a colon, that is not automatic insertion, but manual
insertion, unless I am switched to an automatic mode.

I'm referring to "automatic semicolon insertion" in the sense of the
ECMAScript specification (ES5 section 7.9).
I like either total ; insertion or minimal ; insertion, not a mixture.

The following is valid ECMAScript:
var x = 42;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
It's crappy code, though.
I doubt that is what you mean by "total ; insertion".
To my eyes any other form looks dirty.

My definition of "optimal semicolon placement" would be:
No semicolon that can be omitted due to automatic semicolon
insertion is omitted, and there are no empty statements.
(because empty statements are unnecessary).
I.e., as many semicolons as allowed without adding unnecessary
statements.

Maybe you can say what your "minimal" and "total" means.

[automatic semicolon insertion, aka. ASI]
As I said, that looks dirty.

Oh, it is. Most people can't say when a semicolon will be inserted
and when it won't.
It is the same as omitting indentation, perhaps in the relaistic but
inconsequential believe that indentation only slows down parsing.

Yes. Fine for a minimizer since the output doesn't have to be readable
(but ASI is useless for minimizing since a semicolon isn't longer than
a newline).
Read "should" like "should" in "examples in the faq should have proper
indentation.

They should also have proper semicolons, but a semicolon after a '}'
isn't proper, but misguided.
I do not foolow your reasoning.

I think any statement allows a ; at the end.

And you are wrong. It might seem like it does, but i's actually something
else that happens.
If you write:
for(;;){};
you are not putting a semicolon at the end of the for-statement.
You are putting a semicolon *after* the for-statement. It is not part
of the for-statement. Instead it is part of the *empty statement* that
follows the for-statement, just as:
for(;;){}x=2;
has an expression-statement following the for-statment.

Perhaps our definition of "statement" differs?

That's possible. I believe mine matches the specification ;)
So it is true: "any statement should end with a ;"

No.
Any statement that *can* end with a semicolon *should* do so.
Not all statements can end with a semicolon. They may be *followed*
by a semicolon (representing the empty statement), but they shouldn't.
Perhaps a parser could read that as a spurious statement, like
indentation certainly is spurious to a parser, but the parser should be
wise enough to be "optimizing" and not to spend cycles in the execution
fase on this.

Ofcourse, an empty statement does nothing when executed.
After all present day interpreters are realy realtime
compilars and not linear interpreters of the source text file like the
primeaval version of the MSDOS batch interpreter, that couldn't even
"goto" a linearly previous label.

So I keep my "all statements should end with a ; in examples in the FAQ"
standing.

Only when they can.

/L
 
E

Evertjan.

Stefan Weiss wrote on 16 feb 2011 in comp.lang.javascript:
There's little room for interpretation here (barring syntax extensions
like function declarations in a block). "Statement" is defined in
ECMAScript as

Statement :
Block
VariableStatement
EmptyStatement
ExpressionStatement
IfStatement
IterationStatement
ContinueStatement
BreakStatement
ReturnStatement
WithStatement
LabelledStatement
SwitchStatement
ThrowStatement
TryStatement
DebuggerStatement (ES 5 only)

WRONG.

Those statements may be defined as statements by ECMA.

Them meaning of the word statement is not defined by ECMA.

In my view a statement is a functional unit in a a sourcecode that
stansds on itself and does not implicitly receive input or sent output to
ste adjacent code.
Some of these are specified as being terminated by a semicolon, some
are not (see the list posted by Lasse).

No, I do not think thatr is the case. Perhaps some "need" a ;, and others
can do without.
What you suggest is not not directly related to automatic semicolon
insertion.

I certainly did not bring that into the discussion.
I couln't care less about that, i just like to see all statements end
with a semicolon.
If you add a semicolon in a place where none is expected,
you're introducing an unnecessary new empty statement
(EmptyStatement). FAQ examples shouldn't do that.

I do not think that is either true or important.

FAQ examples should be easy to read and easy to understand.

Therefore they should be nice to the eye.
Deja vu?
<URL:
http://groups.google.com/group/comp.lang.javascript/tree/browse_frm/thr
ead/e6c782d5aef60b85/61d333633ca647cc#doc_a6e44cbcb8b1bba4>

Depends on your pronounciation of "vue". ;-)
 
E

Evertjan.

Lasse Reichstein Nielsen wrote on 16 feb 2011 in comp.lang.javascript:
Evertjan. said:
Lasse Reichstein Nielsen wrote on 15 feb 2011 in
comp.lang.javascript:


What is? The overlooking?

What you call "overlooking", yes. You are allowed to omit some
semicolons from ECMAScript programs where they are otherwise
used to terminate a statement.
If I insert a colon, that is not automatic insertion, but manual
insertion, unless I am switched to an automatic mode.

I'm referring to "automatic semicolon insertion" in the sense of the
ECMAScript specification (ES5 section 7.9).
I like either total ; insertion or minimal ; insertion, not a
mixture.

The following is valid ECMAScript:
var x = 42;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
It's crappy code, though.
I doubt that is what you mean by "total ; insertion".
To my eyes any other form looks dirty.

My definition of "optimal semicolon placement" would be:
No semicolon that can be omitted due to automatic semicolon
insertion is omitted, and there are no empty statements.
(because empty statements are unnecessary).
I.e., as many semicolons as allowed without adding unnecessary
statements.

Maybe you can say what your "minimal" and "total" means.

[automatic semicolon insertion, aka. ASI]
As I said, that looks dirty.

Oh, it is. Most people can't say when a semicolon will be inserted
and when it won't.
It is the same as omitting indentation, perhaps in the relaistic but
inconsequential believe that indentation only slows down parsing.

Yes. Fine for a minimizer since the output doesn't have to be readable
(but ASI is useless for minimizing since a semicolon isn't longer than
a newline).
Read "should" like "should" in "examples in the faq should have
proper indentation.

They should also have proper semicolons, but a semicolon after a '}'
isn't proper, but misguided.
I do not foolow your reasoning.

I think any statement allows a ; at the end.

And you are wrong. It might seem like it does, but i's actually
something else that happens.
If you write:
for(;;){};
you are not putting a semicolon at the end of the for-statement.
You are putting a semicolon *after* the for-statement. It is not part
of the for-statement. Instead it is part of the *empty statement* that
follows the for-statement, just as:
for(;;){}x=2;
has an expression-statement following the for-statment.

Perhaps our definition of "statement" differs?

That's possible. I believe mine matches the specification ;)
So it is true: "any statement should end with a ;"

No.
Any statement that *can* end with a semicolon *should* do so.
Not all statements can end with a semicolon.

What statements cannot end with a ; ?

Please give an example.

If you find one,
probably we differ in definition of the word "statement".
They may be *followed*
by a semicolon (representing the empty statement), but they shouldn't.

If so, why shouldn't they?
Ofcourse, an empty statement does nothing when executed.

So, then it is not realy an empty statement, it would just mean that the
parser jumps over the ; and that is why you call it so.

To me an empty statement is a necessary "noop",
like the first ; in in:

if (boolean) ; else a-7;

Your "empty statement" does does not use runtime cycles after the
parsing.

So why shouldn't it be there,
if it makes the sourse more readable, as I think it does?
Only when they can.

Please give a statement that cannot end with a ;

There are none.
 
D

Dr J R Stockton

In comp.lang.javascript message <[email protected]>
FAQ server wrote on 15 feb 2011 in comp.lang.javascript:
-----------------------------------------------------------------------
FAQ Topic - How can I create a Date object 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.

What is all this '@' stuff, just to scare the newbees off?

[Scaring newbees of in itself might be a laudable passtime,
but not in the FAQ please]

The word is "newbies". Do a Google for "newbees" and for "newbies",
compare the counts, and see which one has a Wikipedia article,
*/
function parseISO8601(dateStringInRange) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,

What nonsense not to allow a
single month or day character, yyyy-[m]m-[d]d,
and allow for external white space.

The author chose to write a validator, and ISO 8601 *requires* mm & dd.
He did not respect "Be strict in what you emit, liberal in what you
accept".
Is external whitespace really part of ISO 8601?

I think not; but 22011-02-169 should not be accepted as a current date.
So perhaps there should be a couple of \b there?
Must the Q "How can I create a Date object from a String?"
realy be answered by a strict following of Extended ISO 8601?
really.

One must use some format definition, preferably excluding FFF but
capable of easy adaptation for that.
date = new Date(NaN), month,
parts = isoExp.exec(dateStringInRange);

if(parts) {
month = +parts[2];

The + is not necessary as both following uses do automagic conversion.

Better to do the conversion once, rather than twice.
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
}

Why not '};' ?
}
return date;
}

I suggest to forget about the rules of ISO 8601,
but to concentrate on it's usefull international acceptance
of the sequence order.

to allow:
yyyy-[m]m-[d]d
yyyy/[m]m/[d]d
yyyy.[m]m.[d]d
yyyymmdd
and not allow external whitespace.

=============================================
function parseYyyymmdd(dateString) {
var date = new Date(NaN);
dateString = dateString.replace(/(\d{4})(\d{2})(\d{2})/,'$1-$2-$3')
var parts = dateString.split(/[-/.]/);

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

Better to match as below, which is moderately flexible and slightly
tested; but external whitespace should be allowed.

DS = "323/11/19";

D = new Date(NaN)
M = DS.match(/\b(\d{3,})(\W)(\d\d?)(\2)(\d\d?)\b/)
if (M) { D.setFullYear(M[1], M[3]-1, M[5])
if (D.getMonth() != +M[3]-1) D.setTime(NaN) }

The text should then say that it will accept any reasonable
representation of a date as Y M D in the range 0100-01-01 to about
275760-09-13, and that ISO's YYYY-MM-DD is included. If the code used
UTC, it would run faster, and "about" would not be needed.

The Topic needs to be changed to imply that the month is Arabic numeric.
 
L

Lasse Reichstein Nielsen

Evertjan. said:
Please give a statement that cannot end with a ;

Switch statements.

The statement:
switch(x){case 42: break;}
cannot end with a semicolon.

If you add a semicolon after it,
switch(x){case 42: break;};
you don't make the switch-statement *end* with a semicolon - you
follow it by an empty statement. The semicolon is not part of the
switch-statement, so it cannot end it.

You can also write:
switch(x){case 42: break;};;;;;;;;;;;;;;;;;;;;
to have 20 empty statements follow the switch-statement. I think we
can agree that that is bad style. It's not invalid syntax, it's just
unnecessary and confusing.

For me, adding the first semicolon is the same. It's only a difference
of degree.

/L
 
L

Lasse Reichstein Nielsen

Evertjan. said:
Those statements may be defined as statements by ECMA.

Them meaning of the word statement is not defined by ECMA.

Actually it is ... in the context of the specification.
When reading the ECMAScript specification, a "statement" is exactly the
syntactic category defined in section 12.

When we discuss ECMAScript in this group, that's also typically what we
mean. If you mean something else by "statement", then you need to say
so (and say what you mean), or we will be miscommunicating.
In my view a statement is a functional unit in a a sourcecode that
stansds on itself and does not implicitly receive input or sent output to
ste adjacent code.

Does an if-statement implicitly send input to its then- or else-branches?
Does an assignment to a variable not implicitly send output to following
statements using that variable?

I.e., I can't use that definition to determine what is a statement and
what is not. I think you have a concept in mind, but this description
might not be sufficient to communicate that concept to the rest of us
(at least it fails to do so to me).

/L
 
E

Evertjan.

Lasse Reichstein Nielsen wrote on 17 feb 2011 in comp.lang.javascript:
Actually it is ... in the context of the specification.
When reading the ECMAScript specification, a "statement" is exactly
the syntactic category defined in section 12.

When we discuss ECMAScript in this group, that's also typically what
we mean. If you mean something else by "statement", then you need to
say so (and say what you mean), or we will be miscommunicating.

That is exactly what I was trying to do.

Defining a group of statements as statements is fine,
but that does not imply that that is the definition of statement.
Does an if-statement implicitly send input to its then- or
else-branches? Does an assignment to a variable not implicitly send
output to following statements using that variable?


You are missing the point.

an if-statement is not the word if but the whole construct:

if (boolean) statement else statement;

A statement can contain statements and a statement can be a group of
statements in {}s.

so:

if (boolean) statement;

ends the statement, but:


if (boolean) statement

does not, as it expects either else or ;


I.e., I can't use that definition to determine what is a statement and
what is not.

Well I can and I doo.

A statement ends when there is no more effect on the next statement.
I think you have a concept in mind, but this description
might not be sufficient to communicate that concept to the rest of us
(at least it fails to do so to me).

Methinks maybe your preconsception that is wrong.

The notion of statement exists from the Algol days or even before that,
and used too be similar to a line of code. Later multiline statements
were conceived but the concept that when a statement ends it has no
influence on the next statement is still paramount.

In Javascript like languages the new line became less important and was
or could be replaced by the ; as an end of statement marker, [though not
completely so, I believe. Cannot find an example now.].

Some statements have such an obvious end, that a ; or a newline is not
necessary, seen the error lenient nature of the parsing.

alert('blah'); is such an example.

But to sat that in that case the ; is an empty statement is just
conseptual end in my view conceptually wrong, as it is not carried from
the runtime parser to the runtime executer.

In my view then ; in alert('blah'); is conceptually necessary for a
complete, logical and optimally readable script. The fact thet the error
of leaving it out is forgiven by the parser does not make that the
standard.

So a complete statement could and should look like this:

if (boolean)
{
statement1;
statement2;
statement3;
}
else
{
statement4;
statement5;
statement6;
}
;

The if statement only ends at my last ;
 
E

Evertjan.

Dr J R Stockton wrote on 17 feb 2011 in comp.lang.javascript:
In comp.lang.javascript message <[email protected]>
FAQ server wrote on 15 feb 2011 in comp.lang.javascript:
-----------------------------------------------------------------------
FAQ Topic - How can I create a Date object 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.

What is all this '@' stuff, just to scare the newbees off?

[Scaring newbees of in itself might be a laudable passtime,
but not in the FAQ please]

The word is "newbies". Do a Google for "newbees" and for "newbies",
compare the counts, and see which one has a Wikipedia article,

Ok, the difference does not visually register, but I knew it as a fact.
*/
function parseISO8601(dateStringInRange) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,

What nonsense not to allow a
single month or day character, yyyy-[m]m-[d]d,
and allow for external white space.

The author chose to write a validator, and ISO 8601 *requires* mm & dd.
He did not respect "Be strict in what you emit, liberal in what you
accept".

Yes perhaps, but we are writing the FAQ for newbies [ok?] and the FAQ-Q was
not about strict validation of the ISO [then the external whitespace should
be disalowed btw], but to give an example of a string parser, and in my
view also stress the importancwe of the y m d sequence.

I think not;

Me too.
but 22011-02-169 should not be accepted as a current date.

It will not be accepted due to the month validation statement

if (parts[1] != date.getMonth() + 1) error

I seem to remember we invented this filter years ago in this NG.
So perhaps there should be a couple of \b there?
Must the Q "How can I create a Date object from a String?"
realy be answered by a strict following of Extended ISO 8601?
really.

One must use some format definition, preferably excluding FFF but
capable of easy adaptation for that.
date = new Date(NaN), month,
parts = isoExp.exec(dateStringInRange);

if(parts) {
month = +parts[2];

The + is not necessary as both following uses do automagic conversion.

Better to do the conversion once, rather than twice.

Better than adding a temporary variable?

could be bet then we should discuss the meaning of beter in this context.
;-)

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

Why not '};' ?
}
return date;
}

I suggest to forget about the rules of ISO 8601,
but to concentrate on it's usefull international acceptance
of the sequence order.

to allow:
yyyy-[m]m-[d]d
yyyy/[m]m/[d]d
yyyy.[m]m.[d]d
yyyymmdd
and not allow external whitespace.

=============================================
function parseYyyymmdd(dateString) {
var date = new Date(NaN);
dateString = dateString.replace(/(\d{4})(\d{2})(\d{2})/,'$1-$2-$3')
var parts = dateString.split(/[-/.]/);

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

Better to match as below, which is moderately flexible and slightly
tested; but external whitespace should be allowed.

For "better" see above.

We also seem to be married to Javascript for "worse".
DS = "323/11/19";

D = new Date(NaN)
M = DS.match(/\b(\d{3,})(\W)(\d\d?)(\2)(\d\d?)\b/)
if (M) { D.setFullYear(M[1], M[3]-1, M[5])
if (D.getMonth() != +M[3]-1) D.setTime(NaN) }

Personally I prefer my example if it is ment to be understood by newbies.
The text should then say that it will accept any reasonable
representation of a date as Y M D in the range 0100-01-01 to about
275760-09-13, and that ISO's YYYY-MM-DD is included. If the code used
UTC, it would run faster, and "about" would not be needed.
YES.

The Topic needs to be changed to imply that the month is Arabic numeric.

??
 
J

John G Harris

Switch statements.

The statement:
switch(x){case 42: break;}
cannot end with a semicolon.

If you add a semicolon after it,
switch(x){case 42: break;};
you don't make the switch-statement *end* with a semicolon - you
follow it by an empty statement. The semicolon is not part of the
switch-statement, so it cannot end it.
<snip>

Even better, ask Evertjan why the following causes IE to say 'syntax
error' :

if (a == 2) switch (a) { case 2: b = 5; break; } ; else b = 6;

John
 
T

Tim Streater

Stefan Weiss said:
On 16/02/11 23:44, Evertjan. wrote:

I think they should be correct, above all. Granted, what you're
suggesting is syntactically correct, too, but it introduces unnecessary
punctuation noise.

I agree code should be nice to the eye, which is why I always match my {
and my } vertically, so it's easy to find the block.

However, Stefan is right about unnecessary punctuation noise. If
Evertjan feels in the need of that, he can always write a regexp.
 
L

Lasse Reichstein Nielsen

John G Harris said:
Even better, ask Evertjan why the following causes IE to say 'syntax
error' :

if (a == 2) switch (a) { case 2: b = 5; break; } ; else b = 6;

Ah, yes, good one!
And it's ofcourse not just IE, but any non-defect ECMAScript
implementations that detect the syntax error here.
/L
 
E

Evertjan.

Lasse Reichstein Nielsen wrote on 17 feb 2011 in comp.lang.javascript:
Ah, yes, good one!
And it's ofcourse not just IE, but any non-defect ECMAScript
implementations that detect the syntax error here.

Poor implementation does not disprove a sound principle.

The whole idea of implementing a switch-statement in Javascript is flawed,
but that does not prove or disprove the concept of statement.

[as usual my "is" is just what I think, like the "is" of any other in this
discussion should be]
 
L

Lasse Reichstein Nielsen

Evertjan. said:
Lasse Reichstein Nielsen wrote on 17 feb 2011 in comp.lang.javascript:
Defining a group of statements as statements is fine,
but that does not imply that that is the definition of statement.

True, it's not the only possible definition of Statement, but it *is*
the one that is assumed unless otherwise stated.

....
You are missing the point.

an if-statement is not the word if but the whole construct:

if (boolean) statement else statement;

.... without the final ';'. It's not part of the if-statement.
A statement can contain statements and a statement can be a group of
statements in {}s.

so:

if (boolean) statement;

ends the statement, but:

It ends the if-statement before the ';', and adds an empty statement
after it.
It would also be ended by another statement, e.g.,
if (boolean) statement while(boolean) other_statement
if (boolean) statement

does not, as it expects either else or ;

No. It does fine without either, e.g.

{ if (boolean) statement }
or
if (boolean) statement var x = expression;
Well I can and I doo.

A statement ends when there is no more effect on the next statement.

I'm afraid that makes no sense to me. Probably because I don't grok
what you mean by effects on another statement.
Methinks maybe your preconsception that is wrong.

The notion of statement exists from the Algol days or even before that,
and used too be similar to a line of code. Later multiline statements
were conceived but the concept that when a statement ends it has no
influence on the next statement is still paramount.

So .... statements are separate and not overlapping?
In Javascript like languages

JavaScript took its grammar from Java, which took it from C. The only thing
JavaScript did different from Java (wrt. semicolons) was to allow omission
of some of them.
In Java
for(;;){};
is also two statements, the latter being empty, and
if (b) for(;;){}; else f();
is a syntax error (as John G Harris pointed out).

Also, the idea that semicolon is a statement terminator isn't universal.
In, e.g., Pascal, it's a statement *separator*, so you write:
x := 2; y := 4
but with no semicolon at the end, and likewise
if (i = 0) then begin
x := 2;
y := 4
end
with no semicolong after "4" or "end".
the new line became less important and was
or could be replaced by the ; as an end of statement marker, [though not
completely so, I believe. Cannot find an example now.].

Example:
var x = 42
/foo/g.test("foo")

The rule in JavaScript is that a semicolon can be omitted if the
current statement could be ended at this point by a semicolon, there
is a newline or the next token is '}' or the end of input, and the
next token, if any, cannot possibly be a continuation of the current
statement.
Some statements have such an obvious end, that a ; or a newline is not
necessary, seen the error lenient nature of the parsing.

Not only is it not necessary, it's simply not part of the statement
grammar for those statements.
alert('blah'); is such an example.

Not really.
alert('blah')
(2+"x").substring(2)
fails because the semicolon is necessary, and newline isn't even
good enough.
But to sat that in that case the ; is an empty statement is just
conseptual end in my view conceptually wrong, as it is not carried from
the runtime parser to the runtime executer.

The grammar is what it is. You can disagree with the design, but whether
it's conceptually wrong or not, it is the way it is.
It seems to me that you have a preconcieved idea of how things should be,
and is now trying to fit the square ECMAScript grammar into a round concept
hole.
In my view then ; in alert('blah'); is conceptually necessary for a
complete, logical and optimally readable script. The fact thet the error
of leaving it out is forgiven by the parser does not make that the
standard.

Are you redefining the word "standard" now?
Allowing omission of the semicolon after alert('blah') (in some cases)
is part of the standard.
The reason to not use that part of the standard is that it doesn't aid
readability and the edge cases are so confuzing that a beginner shouldn't
have to figure it out. Putting in all *statement terminating* semicolons
is a both safe and correct approach. Adding more semicolons than that
is again error-prone because it is at odds with how the language actually
works.
So a complete statement could and should look like this:

if (boolean)
{
statement1;
statement2;
statement3;
}
else
{
statement4;
statement5;
statement6;
}
;

The if statement only ends at my last ;

No it doesn't. It ended at the previous '}'. The ';' is not
part of the if-statement in ECMAScript - independently of your
conceptual model.

And again John G Harris's example:

if (b) if (c) { stmt1; } else { stmt2; }; else { stmt3 };
^
The semicolon after the block containing stmt2 is what you say
an if-statment should look like.
This is a syntax error in ECMAScript.

/L
 
E

Evertjan.

Lasse Reichstein Nielsen wrote on 17 feb 2011 in comp.lang.javascript:
Evertjan. said:
Lasse Reichstein Nielsen wrote on 17 feb 2011 in
comp.lang.javascript:
Defining a group of statements as statements is fine,
but that does not imply that that is the definition of statement.

True, it's not the only possible definition of Statement, but it *is*
the one that is assumed unless otherwise stated.

...
You are missing the point.

an if-statement is not the word if but the whole construct:

if (boolean) statement else statement;

... without the final ';'. It's not part of the if-statement.
A statement can contain statements and a statement can be a group of
statements in {}s.

so:

if (boolean) statement;

ends the statement, but:

It ends the if-statement before the ';', and adds an empty statement
after it.
It would also be ended by another statement, e.g.,
if (boolean) statement while(boolean) other_statement
if (boolean) statement

does not, as it expects either else or ;

No. It does fine without either, e.g.

{ if (boolean) statement }
or
if (boolean) statement var x = expression;
Well I can and I doo.

A statement ends when there is no more effect on the next statement.

I'm afraid that makes no sense to me. Probably because I don't grok
what you mean by effects on another statement.
Methinks maybe your preconsception that is wrong.

The notion of statement exists from the Algol days or even before
that, and used too be similar to a line of code. Later multiline
statements were conceived but the concept that when a statement ends
it has no influence on the next statement is still paramount.

So .... statements are separate and not overlapping?
In Javascript like languages

JavaScript took its grammar from Java, which took it from C. The only
thing JavaScript did different from Java (wrt. semicolons) was to
allow omission of some of them.
In Java
for(;;){};
is also two statements, the latter being empty, and
if (b) for(;;){}; else f();
is a syntax error (as John G Harris pointed out).

Also, the idea that semicolon is a statement terminator isn't
universal. In, e.g., Pascal, it's a statement *separator*, so you
write:
x := 2; y := 4
but with no semicolon at the end, and likewise
if (i = 0) then begin
x := 2;
y := 4
end
with no semicolong after "4" or "end".
the new line became less important and was
or could be replaced by the ; as an end of statement marker, [though
not completely so, I believe. Cannot find an example now.].

Example:
var x = 42
/foo/g.test("foo")

The rule in JavaScript is that a semicolon can be omitted if the
current statement could be ended at this point by a semicolon, there
is a newline or the next token is '}' or the end of input, and the
next token, if any, cannot possibly be a continuation of the current
statement.
Some statements have such an obvious end, that a ; or a newline is
not necessary, seen the error lenient nature of the parsing.

Not only is it not necessary, it's simply not part of the statement
grammar for those statements.
alert('blah'); is such an example.

Not really.
alert('blah')
(2+"x").substring(2)
fails because the semicolon is necessary, and newline isn't even
good enough.
But to sat that in that case the ; is an empty statement is just
conseptual end in my view conceptually wrong, as it is not carried
from the runtime parser to the runtime executer.

The grammar is what it is. You can disagree with the design, but
whether it's conceptually wrong or not, it is the way it is.
It seems to me that you have a preconcieved idea of how things should
be, and is now trying to fit the square ECMAScript grammar into a
round concept hole.
In my view then ; in alert('blah'); is conceptually necessary for a
complete, logical and optimally readable script. The fact thet the
error of leaving it out is forgiven by the parser does not make that
the standard.

Are you redefining the word "standard" now?
Allowing omission of the semicolon after alert('blah') (in some cases)
is part of the standard.
The reason to not use that part of the standard is that it doesn't aid
readability and the edge cases are so confuzing that a beginner
shouldn't have to figure it out. Putting in all *statement
terminating* semicolons is a both safe and correct approach. Adding
more semicolons than that is again error-prone because it is at odds
with how the language actually works.
So a complete statement could and should look like this:

if (boolean)
{
statement1;
statement2;
statement3;
}
else
{
statement4;
statement5;
statement6;
}
;

The if statement only ends at my last ;

No it doesn't. It ended at the previous '}'. The ';' is not
part of the if-statement in ECMAScript - independently of your
conceptual model.

Untrue in my view. My definition of statement is not changed by your
definition of the if-statement.

Ofcourse, if the de definition of the fi-statement says that the ; is not
a necessary part of such, the if-statement ends without that statement,
and the parser can do without. But that is BECAUSE the language condones
the leaving out of the ; as amatter of leniancy.

That does not mean it is not an error to leave it out but that the error
will be forgiven.

And again John G Harris's example:

if (b) if (c) { stmt1; } else { stmt2; }; else { stmt3 };
^
The semicolon after the block containing stmt2 is what you say
an if-statment should look like.
This is a syntax error in ECMAScript.

So that implmentation is in error,
because the implementors forgot to basic logic of a statement.

Describing a valid if-statement ending without
an "else" is not possible in Javascript!!!
And that is a crazy error of the implementation either of the ECMA-
concept or the implementation!!!!

I will show you this here:

if (b) if (c) { stmt1; } else { stmt3 };

Tha above works ok, the 'else' belongs to the "inner" if.

Let us now try to have the else belong to the outer if by closing the
inner if statement:

if (b) if (c) { stmt1; }; else { stmt3 };

This gives an error while it should be perfectly logical script,
equivalent to:

if (b) { if (c) { stmt1; }; } else { stmt3 };
 

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,968
Messages
2,570,153
Members
46,701
Latest member
XavierQ83

Latest Threads

Top