423,851 Members | 2,762 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 423,851 IT Pros & Developers. It's quick & easy.

Check if one date is later then first date

P: n/a
Hi,

Let's say I have 2 dates in the b/m format:

Date 1 and date 2

How do I check whether Date2 is later than Date 1?
Date1. 21-Nov-2006 09:00:00 PM
Date2. 21-Nov-2006 10:00:00 PM

Please advise.

Thanks.

Nov 27 '06 #1
Share this Question
Share on Google+
44 Replies


P: n/a
user said the following on 11/27/2006 8:12 AM:
Hi,

Let's say I have 2 dates in the b/m format:

Date 1 and date 2

How do I check whether Date2 is later than Date 1?
Create Date Objects from them and compare them.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Nov 27 '06 #2

P: n/a

Randy Webb wrote:
user said the following on 11/27/2006 8:12 AM:
Hi,

Let's say I have 2 dates in the b/m format:

Date 1 and date 2

How do I check whether Date2 is later than Date 1?

Create Date Objects from them and compare them.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Yes. I have tried to use setfullyear() ,etc etc and do compare. But the
problem is time. Are there ways to read in the date format specified
above?

Nov 27 '06 #3

P: n/a
user wrote:
Hi,

Let's say I have 2 dates in the b/m format:

Date 1 and date 2

How do I check whether Date2 is later than Date 1?
Date1. 21-Nov-2006 09:00:00 PM
Date2. 21-Nov-2006 10:00:00 PM

Please advise.

Thanks.
You'll need to get both dates into the date object. The Date object
will actually will parse these if you remove the dashes in the date and
replace it with a space. Assuming you can do that...

var date1 = new Date('21 Nov 2006 09:00:00 PM');
var date2 = new Date('21 Nov 2006 10:00:00 PM');

date1 and date2 now have the total milliseconds since some arbitrary
date back in the 70s. Specifically...

date1: 1,164,164,400,000
date2: 1,164,168,000,000

(you can see this number just by doing a document.write(date1*1), which
will force it to cast it as an int.

Once you have your dates parsed you can simply do if (date2 date1).
If you're a little paranoid you can force a cast by if ((date2*1) >
(date1*1)).

You can also subtract date2 from date1 and get the exact time in
milliseconds,seconds,minutes, hours, days, weeks, years between the two
values.

Hope that helps.
--
---------------------------------------------------------------------------
http://www.hunlock.com -- Permanently under construction (And proud of it!)
$FA
Nov 27 '06 #4

P: n/a

pcx99 wrote:
user wrote:
Hi,

Let's say I have 2 dates in the b/m format:

Date 1 and date 2

How do I check whether Date2 is later than Date 1?
Date1. 21-Nov-2006 09:00:00 PM
Date2. 21-Nov-2006 10:00:00 PM

Please advise.

Thanks.

You'll need to get both dates into the date object. The Date object
will actually will parse these if you remove the dashes in the date and
replace it with a space. Assuming you can do that...

var date1 = new Date('21 Nov 2006 09:00:00 PM');
var date2 = new Date('21 Nov 2006 10:00:00 PM');

date1 and date2 now have the total milliseconds since some arbitrary
date back in the 70s. Specifically...

date1: 1,164,164,400,000
date2: 1,164,168,000,000

(you can see this number just by doing a document.write(date1*1), which
will force it to cast it as an int.

Once you have your dates parsed you can simply do if (date2 date1).
If you're a little paranoid you can force a cast by if ((date2*1) >
(date1*1)).

You can also subtract date2 from date1 and get the exact time in
milliseconds,seconds,minutes, hours, days, weeks, years between the two
values.

Hope that helps.
--
---------------------------------------------------------------------------
http://www.hunlock.com -- Permanently under construction (And proud of it!)
$FA
Thanks! I wasn't aware that Date() can cast the above format to epoch!

Nov 27 '06 #5

P: n/a

user wrote:
pcx99 wrote:
user wrote:
Hi,
>
Let's say I have 2 dates in the b/m format:
>
Date 1 and date 2
>
How do I check whether Date2 is later than Date 1?
>
>
Date1. 21-Nov-2006 09:00:00 PM
Date2. 21-Nov-2006 10:00:00 PM
>
Please advise.
>
Thanks.
>
You'll need to get both dates into the date object. The Date object
will actually will parse these if you remove the dashes in the date and
replace it with a space. Assuming you can do that...

var date1 = new Date('21 Nov 2006 09:00:00 PM');
var date2 = new Date('21 Nov 2006 10:00:00 PM');

date1 and date2 now have the total milliseconds since some arbitrary
date back in the 70s. Specifically...

date1: 1,164,164,400,000
date2: 1,164,168,000,000

(you can see this number just by doing a document.write(date1*1), which
will force it to cast it as an int.

Once you have your dates parsed you can simply do if (date2 date1).
If you're a little paranoid you can force a cast by if ((date2*1) >
(date1*1)).

You can also subtract date2 from date1 and get the exact time in
milliseconds,seconds,minutes, hours, days, weeks, years between the two
values.

Hope that helps.
--
---------------------------------------------------------------------------
http://www.hunlock.com -- Permanently under construction (And proud of it!)
$FA

Thanks! I wasn't aware that Date() can cast the above format to epoch!
Hi,

var date1 = new Date(document.form1.date1.value);

document.form1.date1.value is in the time format specified above.

But when i do an alert(date1*1)

it showed me "NaN" instead of integer values.

What did I missed out? Casting?

Nov 27 '06 #6

P: n/a
user wrote:
var date1 = new Date(document.form1.date1.value);

document.form1.date1.value is in the time format specified above.

But when i do an alert(date1*1)

it showed me "NaN" instead of integer values.

What did I missed out? Casting?
You'll need to remove the dashes out of the date value. The parser
handles the date just fine when the date values are separated by spaces
but if you leave the dashes in you'll end up with the type of error you
describe.

---------------------------------------------------------------------------
http://www.hunlock.com -- Permanently under construction (And proud of it!)
$FA
Nov 27 '06 #7

P: n/a

pcx99 wrote:
user wrote:
var date1 = new Date(document.form1.date1.value);

document.form1.date1.value is in the time format specified above.

But when i do an alert(date1*1)

it showed me "NaN" instead of integer values.

What did I missed out? Casting?

You'll need to remove the dashes out of the date value. The parser
handles the date just fine when the date values are separated by spaces
but if you leave the dashes in you'll end up with the type of error you
describe.

---------------------------------------------------------------------------
http://www.hunlock.com -- Permanently under construction (And proud of it!)
$FA

Hi. This is what i did:

x = (document.form1.date1.value).toString();
x = x.replace('-',' ');
alert(x);

But the value of X i received was:

21 Nov-2006 10:00:00 PM

Only 1 dash is removed. Isnt replace supposed to remove all instances?

Nov 27 '06 #8

P: n/a

stevong wrote:
pcx99 wrote:
user wrote:
var date1 = new Date(document.form1.date1.value);
>
document.form1.date1.value is in the time format specified above.
>
But when i do an alert(date1*1)
>
it showed me "NaN" instead of integer values.
>
What did I missed out? Casting?
You'll need to remove the dashes out of the date value. The parser
handles the date just fine when the date values are separated by spaces
but if you leave the dashes in you'll end up with the type of error you
describe.

---------------------------------------------------------------------------
http://www.hunlock.com -- Permanently under construction (And proud of it!)
$FA


Hi. This is what i did:

x = (document.form1.date1.value).toString();
x = x.replace('-',' ');
alert(x);

But the value of X i received was:

21 Nov-2006 10:00:00 PM

Only 1 dash is removed. Isnt replace supposed to remove all instances?
Hi.

I got it right this time

I have to use the g flag:

replace(/-/g,' ');

Now it works fine! Thanks!!

Nov 27 '06 #9

P: n/a
Lee
pcx99 said:
>
user wrote:
>Hi,

Let's say I have 2 dates in the b/m format:

Date 1 and date 2

How do I check whether Date2 is later than Date 1?
Date1. 21-Nov-2006 09:00:00 PM
Date2. 21-Nov-2006 10:00:00 PM

Please advise.

Thanks.

You'll need to get both dates into the date object. The Date object
will actually will parse these if you remove the dashes in the date and
replace it with a space. Assuming you can do that...

var date1 = new Date('21 Nov 2006 09:00:00 PM');
var date2 = new Date('21 Nov 2006 10:00:00 PM');

date1 and date2 now have the total milliseconds since some arbitrary
date back in the 70s. Specifically...

date1: 1,164,164,400,000
date2: 1,164,168,000,000

(you can see this number just by doing a document.write(date1*1), which
will force it to cast it as an int.

Once you have your dates parsed you can simply do if (date2 date1).
If you're a little paranoid you can force a cast by if ((date2*1) >
(date1*1)).
Back when I was first learning programming, I used a multiplication
to simplify the logic of my code and lost points, because multiplying
was more CPU intensive than all of the lines I had avoided. That's
not really true anymore, but it's still more complicated than needed.

Simpler options include:
( date2.getTime() date1.getTime() )
( date2-date1 0 )
or even simply:
( date2 date1 )
--

Nov 27 '06 #10

P: n/a
user wrote:
Yes. I have tried to use setfullyear() ,etc etc and do compare. But
the problem is time. Are there ways to read in the date format
specified above?
http://www.JavascriptToolbox.com/lib/date/

Methods are here for reading in any date format, as long as you provide a
format string.
The returned Date objects can then be compared using the isBefore or isAfter
methods added to the Date prototype.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Nov 27 '06 #11

P: n/a
In comp.lang.javascript message
<2T*****************@newssvr25.news.prodigy.net> , Mon, 27 Nov 2006
13:38:06, pcx99 <x@x.comwrote:
>user wrote:
>Hi,
Let's say I have 2 dates in the b/m format:
???
Eschew quaint abbreviations.
> Date 1 and date 2
How do I check whether Date2 is later than Date 1?
Date1. 21-Nov-2006 09:00:00 PM
Date2. 21-Nov-2006 10:00:00 PM
Please advise. Thanks.

You'll need to get both dates into the date object. The Date object
will actually will parse these if you remove the dashes in the date and
replace it with a space. Assuming you can do that...

var date1 = new Date('21 Nov 2006 09:00:00 PM');
var date2 = new Date('21 Nov 2006 10:00:00 PM');

date1 and date2 now have the total milliseconds since some arbitrary
date back in the 70s. Specifically...
It is not an arbitrary date; it is 1970-01-01 00:00:00 GMT.
>date1: 1,164,164,400,000
date2: 1,164,168,000,000
The first figure corresponds to Wed Nov 22 03:00:00 UTC 2006. Evidently
you do not recall that dates are generally assumed by Javascript to be
in the user's time zone using the Summer Time rules currently
appropriate (according to the browser/OS).
>(you can see this number just by doing a document.write(date1*1), which
will force it to cast it as an int.
Not to an int, but to a Number. Not a cast, which is a
re-interpretation, rather than a transformation, of a bit pattern. For
the purpose, we deprecate multiplication; use unary +, as per the FAQ.
>Once you have your dates parsed you can simply do if (date2 date1).
If you're a little paranoid you can force a cast by if ((date2*1) >
naive
>(date1*1)).
>You can also subtract date2 from date1 and get the exact time in
milliseconds,seconds,minutes, hours, days, weeks, years between the two
values.
You forgot months! One can get the exact time in milliseconds (ignoring
Leap Seconds); but "exact" conversion to days weeks months years, all of
which are of variable length, is unrealistic.

It's a good idea to read the newsgroup and its old FAQ. See below.

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v6.05 IE 6
<URL:http://www.jibbering.com/faq/ Old RC FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Nov 27 '06 #12

P: n/a
Dr J R Stockton wrote:
It is not an arbitrary date; it is 1970-01-01 00:00:00 GMT.
This is an arbitrary date. It is constant but the date itself is
arbitrary. There was no reason to pick that particular date other than
for the fact that at one point in time someone did and it's been a part
of various computer languages that resolve julian dates ever since.
>date1: 1,164,164,400,000
date2: 1,164,168,000,000

The first figure corresponds to Wed Nov 22 03:00:00 UTC 2006. Evidently
you do not recall that dates are generally assumed by Javascript to be
in the user's time zone using the Summer Time rules currently
appropriate (according to the browser/OS).
Evidently for the problem described it does not matter. Since we're
doing a relative check between two dates it doesn't matter if the user
is in china and the parser is resolving everything to GMT as long as
both dates resolve to the same timezone which they will unless a
time-zone deliberately gets into the mix, which the quaint b/c format
seems not to allow.
>(you can see this number just by doing a document.write(date1*1), which
will force it to cast it as an int.

Not to an int, but to a Number. Not a cast, which is a
re-interpretation, rather than a transformation, of a bit pattern. For
the purpose, we deprecate multiplication; use unary +, as per the FAQ.
document.write(date1); ----[object]
document.write(date1*1); --very long integer.

+ is a concatenation element in javascript and may yield unpredictable
results. * guaranteed the conversion without risking concatenation or
requiring additional elements to contain concatenation which would
increase the complexity.

I will, however, concede that in a formal setting date1.getTime() would
be the best practice.
You forgot months! One can get the exact time in milliseconds (ignoring
Leap Seconds); but "exact" conversion to days weeks months years, all of
which are of variable length, is unrealistic.
I'm sorry but this is wrong. If you have the exact number of
miliseconds between two dates as well as the two original starting and
ending dates you can indeed find the exact number of days, weeks,
months, years and any other element you wish to find. You can test this
for yourself by creating a date object for today, and a date object for
some point in the future (even a future which includes a leap year)
convert both to julian numbers, obtain the difference, add the
difference to the original julian number (today), and you'll find on
inspecting the new date that the date, year, month, etc all match up to
your original future date despite the "inexactness" of dealing with leap
years and all that other stuff.

If the date object is able to find this, it does indeed mean that exact
conversions are exactly what is happening which means if you want the
information badly enough, you will be able to get it from elegant
time/date algorithms right on down to setting up a stash of counters and
marking any changes as you brute force a date object second by second
between the two values.
It's a good idea to read the newsgroup and its old FAQ. See below.
And it's a good idea to not be so concerned with the leaves on the trees
that you get lost in the forest. Just because the answer is not the way
YOU would have done it doesn't mean that it's not a correct or valid
answer, this is especially true when the appeal to authority gets kicked
up to textbooks or, in this case, FAQs.
---------------------------------------------------------------------------
http://www.hunlock.com -- Permanently under construction (And proud of it!)
$FA
Nov 28 '06 #13

P: n/a
pcx99 said the following on 11/28/2006 5:03 AM:

<snip>
+ is a concatenation element in javascript and may yield unpredictable
results.
That is simply false.

myString = "123";
myNewString = +myString;
alert(typeof myString);

Do you know of a browser that doesn't give number as the type of
myNewString? Or, can you give an example of where using + to convert
from String to Number will give "unpredictable results"?

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Nov 28 '06 #14

P: n/a
Randy Webb wrote:
pcx99 said the following on 11/28/2006 5:03 AM:

<snip>
>+ is a concatenation element in javascript and may yield unpredictable
results.

That is simply false.

myString = "123";
myNewString = +myString;
alert(typeof myString);

Do you know of a browser that doesn't give number as the type of
myNewString? Or, can you give an example of where using + to convert
from String to Number will give "unpredictable results"?

document.write(+date1);

Just fine does what we all expect and want. Now, given the tutorial
nature of this subject what if the end user decides to be a little bit
more descriptive with what he types into his editor? I don't know about
you but when I'm following new code my output gets very descriptive.

document.write('example: '+date1);

Not so false is it? In fact the result is no longer a julian integer
but a date string.

Now compare that if the user expands on my original example..

document.write('example: '+date1*1);

Still a julian integer. Using a concatenation character when discussing
new concepts with people introduces unnecessary risk into the discussion
it's as simple as that.

But as I said. I erred in not using datex.getTime() so if you want to
beat me up over something at least pick something that makes sense.

---------------------------------------------------------------------------
http://www.hunlock.com -- Permanently under construction (And proud of it!)
$FA
Nov 28 '06 #15

P: n/a
pcx99 said the following on 11/28/2006 11:41 AM:
Randy Webb wrote:
>pcx99 said the following on 11/28/2006 5:03 AM:

<snip>
>>+ is a concatenation element in javascript and may yield
unpredictable results.

That is simply false.

myString = "123";
myNewString = +myString;
alert(typeof myString);

Do you know of a browser that doesn't give number as the type of
myNewString? Or, can you give an example of where using + to convert
from String to Number will give "unpredictable results"?


document.write(+date1);

Just fine does what we all expect and want. Now, given the tutorial
nature of this subject what if the end user decides to be a little bit
more descriptive with what he types into his editor? I don't know about
you but when I'm following new code my output gets very descriptive.

document.write('example: '+date1);
document.write('example: ' + (+date1));

+ isn't "unpredictable". What predicts how it will act is how it is used.
Not so false is it? In fact the result is no longer a julian integer
but a date string.
Now compare that if the user expands on my original example..

document.write('example: '+date1*1);
And still an integer in my example as well.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Nov 28 '06 #16

P: n/a
Randy Webb wrote:
pcx99 said the following on 11/28/2006 11:41 AM:
>
document.write('example: ' + (+date1));

+ isn't "unpredictable". What predicts how it will act is how it is used.

And still an integer in my example as well.

Yes indeed, I'm well aware of this and was aware of this when I wrote
the example. In the absence of the proper getTime method, using
multiplication was still the better choice since it allowed for
unpredictable behavior by the end user in learning the concept. In
short I used javascript's order of operation to my advantage to enhance
the robustness of the code. ;) As I said in one of the parent posts...
"(multiplication) guaranteed the conversion without risking
concatenation or requiring additional elements to contain concatenation
which would increase the complexity."

And that's all I have to say about that.

---------------------------------------------------------------------------
http://www.hunlock.com -- Permanently under construction (And proud of it!)
$FA
Nov 28 '06 #17

P: n/a
In comp.lang.javascript message
<7Q***************@newssvr27.news.prodigy.net>, Tue, 28 Nov 2006
10:03:47, pcx99 <x@x.comwrote:
>Dr J R Stockton wrote:
>It is not an arbitrary date; it is 1970-01-01 00:00:00 GMT.

This is an arbitrary date. It is constant but the date itself is
arbitrary. There was no reason to pick that particular date other than
for the fact that at one point in time someone did and it's been a part
of various computer languages that resolve julian dates ever since.

It is not an arbitrary date; it is a reasonably well-chosen date.

Evidently you do not know the proper meaning of Julian Date. Of course,
you are not alone; IBM do not either. Julian Date is a count of days
from Julian Calendar BC 4713-01-01 12:00:00 GMT.
>>date1: 1,164,164,400,000
date2: 1,164,168,000,000
The first figure corresponds to Wed Nov 22 03:00:00 UTC 2006.
Evidently
you do not recall that dates are generally assumed by Javascript to be
in the user's time zone using the Summer Time rules currently
appropriate (according to the browser/OS).

Evidently for the problem described it does not matter. Since we're
doing a relative check between two dates it doesn't matter if the user
is in china and the parser is resolving everything to GMT as long as
both dates resolve to the same timezone which they will unless a time-
zone deliberately gets into the mix, which the quaint b/c format seems
not to allow.
It does not matter for the user's coding.

It DOES matter that you have, either through carelessness or through
lack of understanding, made a false statement which might deceive
innocent readers of your article.
>>(you can see this number just by doing a document.write(date1*1), which
will force it to cast it as an int.
Not to an int, but to a Number. Not a cast, which is a
re-interpretation, rather than a transformation, of a bit pattern. For
the purpose, we deprecate multiplication; use unary +, as per the FAQ.
>document.write(date1); ----[object]
That should give the date as a string, something like
Tue Nov 21 21:00:00 UTC 2006
Did you test your assertion of [object] ?
>document.write(date1*1); --very long integer.

+ is a concatenation element in javascript and may yield unpredictable
results.
Incorrect. It is an addition operator where both operands are Number;
if it has a single argument, it yields a Number; if both operands are
Boolean, it coverts them to Number and adds them. If just one argument
is a String, it converts the other to String and concatenates, If both
are strings, it concatenates. Its results are fully defined by
ECMA-262, and I know of no case in which a reputable recent browser gets
it wrong.
* guaranteed the conversion without risking concatenation or
requiring additional elements to contain concatenation which would
increase the complexity.
No additional elements are required before a unary + ; a space may be
needed to prevent it being half of a ++. Try X = 3-+true for example.
>I will, however, concede that in a formal setting date1.getTime() would
be the best practice.
But date1.valueOf() while in fact calling for exactly the same
operation is less likely to be confused by a reader with the concept of
getting the time of day. And unary + is simpler and should be faster.
>You forgot months! One can get the exact time in milliseconds (ignoring
Leap Seconds); but "exact" conversion to days weeks months years, all of
which are of variable length, is unrealistic.

I'm sorry but this is wrong. If you have the exact number of
miliseconds between two dates as well as the two original starting and
ending dates you can indeed find the exact number of days, weeks,
months, years and any other element you wish to find. You can test
this for yourself by creating a date object for today, and a date
object for some point in the future (even a future which includes a
leap year) convert both to julian numbers, obtain the difference, add
the difference to the original julian number (today), and you'll find
on inspecting the new date that the date, year, month, etc all match up
to your original future date despite the "inexactness" of dealing with
leap years and all that other stuff.
That proves nothing. A reversible conversion is not necessarily a
correct conversion.

>It's a good idea to read the newsgroup and its old FAQ. See below.

And it's a good idea to not be so concerned with the leaves on the
trees that you get lost in the forest. Just because the answer is not
the way YOU would have done it doesn't mean that it's not a correct or
valid answer, this is especially true when the appeal to authority gets
kicked up to textbooks or, in this case, FAQs.
That leaves you with only the resource of appealing to your own
authority or that of the unfortunate who had the task of teaching you.
You should also read ECMA-232.

--
(c) John Stockton, Surrey, UK. ??*@merlyn.demon.co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demon.co.uk/- FAQish topics, acronyms, & links.
Check boilerplate spelling -- error is a public sign of incompetence.
Never fully trust an article from a poster who gives no full real name.
Nov 29 '06 #18

P: n/a
In comp.lang.javascript message <xo********************@telcove.net>,
Tue, 28 Nov 2006 11:50:10, Randy Webb <Hi************@aol.comwrote:
>
document.write('example: ' + (+date1));
The ignorant should be unformed that the inner parentheses above are
computationally superfluous. Some may consider that they aid
legibility.

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk DOS 3.3, 6.20 ; WinXP.
Web <URL:http://www.merlyn.demon.co.uk/- FAQqish topics, acronyms & links.
PAS EXE TXT ZIP via <URL:http://www.merlyn.demon.co.uk/programs/00index.htm>
My DOS <URL:http://www.merlyn.demon.co.uk/batfiles.htm- also batprogs.htm.
Nov 29 '06 #19

P: n/a
Dr J R Stockton said the following on 11/28/2006 3:36 PM:
In comp.lang.javascript message <xo********************@telcove.net>,
Tue, 28 Nov 2006 11:50:10, Randy Webb <Hi************@aol.comwrote:
>>
document.write('example: ' + (+date1));

The ignorant should be unformed that the inner parentheses above are
computationally superfluous.
You should proof read more carefully. I don't expect you to understand
why but the "inner parentheses" are there for a very good reason. And,
they are *not* superfluous. They have a very specific reason for being
there.
Some may consider that they aid legibility.
Among other reasons. But I didn't add them for legibility.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Nov 29 '06 #20

P: n/a
Dr J R Stockton wrote:
In comp.lang.javascript message
<7Q***************@newssvr27.news.prodigy.net>, Tue, 28 Nov 2006
10:03:47, pcx99 <x@x.comwrote:
>Dr J R Stockton wrote:
It is not an arbitrary date; it is a reasonably well-chosen date.
Still arbitrarily set. It could have been 01/01/1969 or 10/25/1955,
from a coding perspective there's no difference between the two.
Evidently you do not know the proper meaning of Julian Date. Of course,
you are not alone; IBM do not either. Julian Date is a count of days
from Julian Calendar BC 4713-01-01 12:00:00 GMT.
Evidently you're not aware of the function of Julian dates in the
computer sciences. COBOL uses 01/01/1601. NASA uses 5/24/1968. The
PICK OS used 01/01/1965. Astronomers have their own julian system and
there are various other niche systems. These are all Julian date
systems which represents the passage of time with a simple integer.
There is no single Julian date, there is an original Julian calendar and
there are a plethora of additional Julian systems with different
starting dates. The selection of 1/1/1970 was an arbitrary decision by
the developers of the language, 1/2/1970 would have worked just as well
as far as javascript is concerned.

It does not matter for the user's coding.

It DOES matter that you have, either through carelessness or through
lack of understanding, made a false statement which might deceive
innocent readers of your article.
Not. There's no error with the code. It will parse both dates
perfectly great providing differing time zones are not inserted into the
string being parsed which, given the original data, is not a factor.
Which means the browser's time-zones will be used which means the
relative check between date1 and date2 will be flawless. Even if the
original data originated in a different time zone it still does not
matter because the code is only doing a relative check between the two
dates.

The time zone is simply not a factor in the problem or solution.
>+ is a concatenation element in javascript and may yield unpredictable
results.

Incorrect. It is an addition operator where both operands are Number;
if it has a single argument, it yields a Number; if both operands are
Boolean, it coverts them to Number and adds them. If just one argument
is a String, it converts the other to String and concatenates, If both
are strings, it concatenates. Its results are fully defined by
ECMA-262, and I know of no case in which a reputable recent browser gets
it wrong.
This is the relevant part from your quote. This is what I was avoiding
by using multiplication instead of addition...
>If just one argument
is a String, it converts the other to String and concatenates
The problem is that date1 is not an integer, it is an object. The
multiplication forced it to behave as an integer for the purpose of the
demonstration, however if + is used to force the transformation the
example risked failing because document.writeln('testing: '+date1) would
return a date string and not a date integer which is what I was discussing.

I didn't assume the end user would enter the example as entered, I
assumed that while exploring new code the user would expand on the
document.write string for debugging purposes which means using +date1
would yield unpredictable results if the user went from...

document.writeln(+date1); (shows integer value)
to
document.writeln('testing: '+date1); (shows string value, not what we
wanted).

By using multiplication in my example, I used javascript's order of
operation to my advantage since multiplication takes priority over
addition (and concatenation) which means that even if the user expands
on my original example, it will still work.

document.writeln('testing: '+date1*1); (still an integer).

Randy Webb correctly noted that

document.writeln('testing: '+(+date1)); (still an integer)

would resolve everything to the satisfaction of the great and holy faqs,
but as I said, I deliberately chose multiplication to contain any chance
of concatenation and to simplify the readability of the code for people
learning a new concept.

I think we've all agreed that next time I'll just use date1.getTime()
which will avoid this sort of totally pointless nitpicking.
>>You forgot months! One can get the exact time in milliseconds (ignoring
Leap Seconds); but "exact" conversion to days weeks months years, all of
which are of variable length, is unrealistic.
I'm sorry but this is wrong. If you have the exact number of
miliseconds between two dates as well as the two original starting and
That proves nothing. A reversible conversion is not necessarily a
correct conversion.
To which I can only conclude you have no understanding of how the
internal julian system works and any further discussion is pointless
until you make an effort to learn it. Suffice it to say that given any
starting date and a julian integer I can calculate the exact destination
date both forward and reverse and any other element you would like from
number of days, weeks, years, even the number of leap years between the
two dates.

How do I know this is true? Because to javascript all date/time are
julian integers and from that it calculates the day of the week, the
week of the year, and tons of other nifty, useful information regardless
of leap years, and other uncertainties in our real world calendars. It
does all this millions of time every single day, every time someone does
ANYTHING with a date object.
That leaves you with only the resource of appealing to your own
authority or that of the unfortunate who had the task of teaching you.
You should also read ECMA-232.
Did your FAQs and ECMA-232 teach you the following?
>document.write('example: ' + (+date1));

The ignorant should be unformed that the inner parentheses above are
computationally superfluous. Some may consider that they aid
legibility.

Unformed is right ;) Try taking out the parenthesis around date1 and
seeing how superfluous they really are -- oh and don't go thinking
++date1 is going to make things right with the world either ;)

So pardon me if I continue to march to my own drummer because books are
tools to serve us, if books are our masters then we are the tools ;)
---------------------------------------------------------------------------
http://www.hunlock.com -- Permanently under construction (And proud of it!)
$FA
Nov 30 '06 #21

P: n/a
pcx99 said the following on 11/29/2006 11:06 PM:

<snip>
Randy Webb correctly noted that

document.writeln('testing: '+(+date1)); (still an integer)

would resolve everything to the satisfaction of the great and holy faqs,
It has nothing to do with your concept of "great and holy faqs" and my
comment had absolutely nothing to do with dates. My issue was with your
statement:

<quote>
+ is a concatenation element in javascript and may yield unpredictable
results.
</quote>

It had to do with that false statement. Date object or not.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Nov 30 '06 #22

P: n/a
pcx99 wrote:
Evidently you're not aware of the function of Julian dates in the
computer sciences.
Before you go correctly the good doctor about dates in this group, you
should probably demonstrate a deep and broad knowledge of the topic. Few
have learned and tried to document date calculation logic and calendar
systems as deeply as Mr. Stockton has.
Suffice it to say that given
any starting date and a julian integer I can calculate the exact
destination date both forward and reverse and any other element you
would like from number of days, weeks, years, even the number of leap
years between the two dates.
How many months are there between Jan 31 and Feb 1 (1 day)?
How about between Jan 1 and Feb 28 (59 days)?

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Nov 30 '06 #23

P: n/a
Matt Kruse said the following on 11/30/2006 12:52 AM:
pcx99 wrote:
>Evidently you're not aware of the function of Julian dates in the
computer sciences.

Before you go correctly the good doctor about dates in this group, you
should probably demonstrate a deep and broad knowledge of the topic. Few
have learned and tried to document date calculation logic and calendar
systems as deeply as Mr. Stockton has.
Very very true and couldn't be said better.
>Suffice it to say that given
any starting date and a julian integer I can calculate the exact
destination date both forward and reverse and any other element you
would like from number of days, weeks, years, even the number of leap
years between the two dates.

How many months are there between Jan 31 and Feb 1 (1 day)?
How about between Jan 1 and Feb 28 (59 days)?
<humor>
<jumping up and down raising hand screaming "I know, I know">
Between being inclusive or exclusive?<giggle>
</humor>

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Nov 30 '06 #24

P: n/a
Randy Webb <Hi************@aol.comwrites:
Dr J R Stockton said the following on 11/28/2006 3:36 PM:
>Randy Webb <Hi************@aol.comwrote:
>>document.write('example: ' + (+date1));
The ignorant should be unformed that the inner parentheses above are
computationally superfluous.

You should proof read more carefully. I don't expect you to understand
why but the "inner parentheses" are there for a very good reason. And,
they are *not* superfluous. They have a very specific reason for being
there.
Is the answer there ?
http://www.crockford.com/javascript/jsmin.html

Arnaud
--
Arnaud DIEDEREN
Software Developer
IONIC Software
Rue de Wallonie, 18 - 4460 Grace-Hollogne - Belgium
Tel: +32.4.3640364 - Fax: +32.4.2534737
mailto:ad@ionicsoft.com
http://www.ionicsoft.com
Nov 30 '06 #25

P: n/a
Randy Webb wrote:
It has nothing to do with your concept of "great and holy faqs" and my
comment had absolutely nothing to do with dates. My issue was with your
statement:

<quote>
+ is a concatenation element in javascript and may yield unpredictable
results.
</quote>

It had to do with that false statement. Date object or not.
It depends on your definition of unpredictable results. If you go from
a machine perspective then yes, you can -- obviously -- nitpick all you
want to try and justify your existence by being *THE AUTHORITY* on all
such matters. If you go from a human perspective then you can -- just
as obviously -- justify that concatenation elements do indeed have the
capacity to introduce unpredictable results from people who are learning
new language concepts and may not have a deep understanding of the order
of operation. Even the "good doctor" failed this one basic task, by
missing the importance of the parenthesis and would have fallen into the
exact trap I was trying to avoid by using multiplication instead of
addition.

So you say tomato and I say tamato, how you see the "problem" depends on
how you approach the problem. If you go soley from the textbooks and
faqs in the proper method of doing things then yes, +() is the most
efficient and standard. If you go strictly by real world usage given
the scope of the problem and the necessity to keep it simple and
relatively foolproof then obviously +() wasn't the best method to use
since the pitfalls snared even a self-proclaimed expert in the process.

I'm pretty sure I said I was done with this particular aspect of the
discussion but I've got a cold this morning so I'm cranky with time on
my hands, bad combo ;)

---------------------------------------------------------------------------
http://www.hunlock.com -- Permanently under construction (And proud of it!)
$FA
Nov 30 '06 #26

P: n/a
Matt Kruse wrote:
pcx99 wrote:
>Evidently you're not aware of the function of Julian dates in the
computer sciences.

Before you go correctly the good doctor about dates in this group, you
should probably demonstrate a deep and broad knowledge of the topic. Few
have learned and tried to document date calculation logic and calendar
systems as deeply as Mr. Stockton has.
Mr. Stockton argued that timezones were a factor in this discussion --
they weren't. Mr. Stockton argued that using addition instead of
multiplication was the correct way to explain the date concepts to the
"unformed" and then fell into the exact same trap I was trying to avoid
by failing to understand the importance of the parenthesis to contain
the concatenation when Randy Webb was discussing the issue with me. And
Mr. Stockton has completely failed to demonstrate any knowledge about
how exactly Julian dates do work inside javascript to the point of
completely misunderstanding just how powerful they actually are in
resolving unique, repeatable, individual, and verifiable dates given
nothing more than a single Julian integer.

And, yet, I have not demonstrated a deep and broad knowledge of this
subject -- how exactly?

>Suffice it to say that given
any starting date and a julian integer I can calculate the exact
destination date both forward and reverse and any other element you
would like from number of days, weeks, years, even the number of leap
years between the two dates.

How many months are there between Jan 31 and Feb 1 (1 day)?
How about between Jan 1 and Feb 28 (59 days)?
It's not a hard question, until a full month has actually passed the
answer is zero. In this case the answer to the first question is zero
months 1 day and x/mins/secs hours, In the second case the answer is 1
month 28 days and x hours/mins/secs. If you would like the answers can
be resolved to fractions of months which would make the first answer
non-zero (but still not one).

Are you suggesting that any halfway competent programmer would be unable
to resolve the dates? ;)
---------------------------------------------------------------------------
http://www.hunlock.com -- Permanently under construction (And proud of it!)
$FA
Nov 30 '06 #27

P: n/a
pcx99 wrote:
<snip>
... . If you go soley from the textbooks and
faqs in the proper method of doing things then yes, +() is the most
efficient and standard.
It is the fastest type-converting-to-number operator/method (by between
5 and 700%, depending on the environment and which alternative is used
for comparison).
If you go strictly by real world usage given
the scope of the problem and the necessity to keep it simple and
relatively foolproof then obviously +() wasn't the best method to use
... .
<snip>

The clearest type-conversion to number method is:-

Number(date1)

- as it is virtually self-documenting.

There no type-converting methods between the clearest and the fastest
that deserve consideration.

Richard.

Nov 30 '06 #28

P: n/a
Richard Cornford wrote:
>
The clearest type-conversion to number method is:-

Number(date1)

- as it is virtually self-documenting.

There no type-converting methods between the clearest and the fastest
that deserve consideration.

Richard.
I've already conceded that date1.getTime() would have been the proper
choice to use instead of *1. Number would be the second best choice
and I am ashamed to admit that I never considered it either in the
original answer to the problem nor in the follow-up.
---------------------------------------------------------------------------
http://www.hunlock.com -- Permanently under construction (And proud of it!)
$FA
Nov 30 '06 #29

P: n/a
pcx99 wrote:
>How many months are there between Jan 31 and Feb 1 (1 day)?
How about between Jan 1 and Feb 28 (59 days)?
It's not a hard question, until a full month has actually passed the
answer is zero.
What is a "full month"? A month does not specify an amount of time, but a
relative period.
In this case the answer to the first question is
zero months 1 day and x/mins/secs hours
Days and hours are irrelevant, I just asked about months.

Your answer differs with that of my database:

1SELECT DATEDIFF(mm,'January 31, 2006','February 1, 2006')
2go
-----------
1
In the second case the
answer is 1 month 28 days and x hours/mins/secs.
The month has ticked from Jan to Feb in each example - why is there a
difference in the number of months between the two?
If you would like
the answers can be resolved to fractions of months which would make
the first answer non-zero (but still not one).
How would you resolve it to a fraction of a month, when you don't really
know how long a "month" is?

IMO, the logical way to compute a datediff for period month is to see how
many month changes happen between two dates. So the number of months between
Jan 31 and Feb 1 is 1, because one month change has happened.

Calculating number of months difference for an arbitrary time period (say,
31 days) is impossible without knowing the actual start date.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Nov 30 '06 #30

P: n/a
Matt Kruse wrote:
pcx99 wrote:
>>How many months are there between Jan 31 and Feb 1 (1 day)?
How about between Jan 1 and Feb 28 (59 days)?
It's not a hard question, until a full month has actually passed the
answer is zero.

What is a "full month"? A month does not specify an amount of time, but a
relative period.

A decent question. You can average the months... ((daysinyear)/12),
this is good for fractional answers (4.25 months). You can also do a
literal reading, as your database query returned.

However, countdown timers and accounting systems require a more precise
mapping to real world calendars.
>In this case the answer to the first question is
zero months 1 day and x/mins/secs hours

Days and hours are irrelevant, I just asked about months.

Your answer differs with that of my database:

1SELECT DATEDIFF(mm,'January 31, 2006','February 1, 2006')
2go
-----------
1
>In the second case the
answer is 1 month 28 days and x hours/mins/secs.

The month has ticked from Jan to Feb in each example - why is there a
difference in the number of months between the two?
Because a full month passed in the second example. If you had given me
Jan 2 as the start date instead of Jan 1 then the answer would have
been zero months, 58 days because no full real world month had passed
between the two dates. If you had given me Jan 1 1:05am as the start
date it would have been 58 days as well instead of 1 month 28 days all
because of 5 mins.
>If you would like
the answers can be resolved to fractions of months which would make
the first answer non-zero (but still not one).

How would you resolve it to a fraction of a month, when you don't really
know how long a "month" is?
For fractional purposes a month is exactly: ((daysinyear)/12) --
daysinyear is a variable thanks to leap years useful for giving
estimates and approximations.
IMO, the logical way to compute a datediff for period month is to see how
many month changes happen between two dates. So the number of months between
Jan 31 and Feb 1 is 1, because one month change has happened.
This is one way to look at it, however strictly speaking, a month's
period of time has not passed. This is unacceptable for accounting
purposes and countdown timers which would be in danger of rendering an
incorrect number of months in the display. Go ask your payroll manager
to pay you based on datediff and you'll be laughed out of the office ;)
Calculating number of months difference for an arbitrary time period (say,
31 days) is impossible without knowing the actual start date.
This is true, you can't really calculate anything without a starting
date, you can't calculate much without an ending date either!
Fortunately all such problems of this nature will include both a
starting and ending date ;)
---------------------------------------------------------------------------
http://www.hunlock.com -- Permanently under construction (And proud of it!)
$FA
Nov 30 '06 #31

P: n/a
Arnaud Diederen (aundro) wrote:
Is the answer there ?
http://www.crockford.com/javascript/jsmin.html

Arnaud

No, though I can see why you would.

In the example we are discussing date1 is a date object. Worse, it's a
smart object. The value it returns depends on how it is used in javascript.

If you say writeln(date1) it's going to return a date string "January 1
2006" or something along that line. If you say writeln(+date1) then
it's going to return an integer value that the date object can convert
back into a string date. This integer value is a Julian date, it's the
number of milliseconds since 1/1/1970 and the date the object is
holding. (the date and integers below are pseudo, they are not exact
representations).

So here are a few examples:

date1 = string ( January 1 2006 )
date1*1= integer ( 1928392932 )
+date1 = integer ( 1928392932 )
"testing "+date1 = string+date string (testing January 1 2006)
"testing "+date1*1= string+integer (testing 1928392932)
"testing "+(+date1) = string+integer (testing 1928392932)

The parenthesis tell javascript to immediately do the operation between
the parenthesis first, before anything else is done with the expression.
So in this case they are not decorative or superfluous, they're there
to ensure that date1 is displayed as an integer and not a string. No
parenthesis is required with multiplication because multiplication is
always done before addition/subtraction and concatenation.

---------------------------------------------------------------------------
http://www.hunlock.com -- Permanently under construction (And proud of it!)
$FA
Nov 30 '06 #32

P: n/a
pcx99 wrote:
>What is a "full month"? A month does not specify an amount of time,
but a relative period.
A decent question. You can average the months... ((daysinyear)/12),
this is good for fractional answers (4.25 months).
365/12 = 30.41 days.
So Jan 31 - Mar 1 isn't even 1 month?
This is one way to look at it, however strictly speaking, a month's
period of time has not passed.
A "month" is not a period of time. So there is no way to determine if it has
passed.
This is unacceptable for accounting
purposes and countdown timers which would be in danger of rendering an
incorrect number of months in the display. Go ask your payroll
manager to pay you based on datediff and you'll be laughed out of the
office ;)
I'm not sure how payroll matters for monthly calculations.

The only real answer to the question of "How many months have passed between
two dates?" is "That depends on how you define it."

In the past, I've used a formula like this, which I think makes sense:

For two dates D1 and D2 (D2>D1), the number of months difference is
12*(Y2-Y1)+(M2-M1)-((D2-D1<0)?1:0)

So, examples:

Jan 31, 2005 : Y=2005, M=1, D=31
Mar 1, 2005 : Y=2005, M=3, D=1

12*(2005-2005)+(3-1)-((1-31<0)?1:0) = 0 + 2 - 1 = 1

Nov 20, 2005 : Y=2005, M=11, D=20
Feb 12, 2006 : Y=2006, M= 2, D=12

12*(2006-2005)+(2-11)-((12-20<0)?1:0) = 12 + -9 - 1 = 2

Nov 20, 2005 : Y=2005, M=11, D=20
Feb 21, 2006 : Y=2006, M= 2, D=21

12*(2006-2005)+(2-11)-((21-20<0)?1:0) = 12 + -9 - 0 = 3

I think this matches well with what people mean in conversation when they
ask if a month has passed, for example. If today is the 30th, and you say
"it's been exactly 1 month since X" you would expect X to have been on the
30th of the last month. Except if today is March 30th, in which "exactly
last month" is quite ambiguous :)

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Nov 30 '06 #33

P: n/a
Matt Kruse wrote:
The only real answer to the question of "How many months have passed between
two dates?" is "That depends on how you define it."

I think we can both agree to this. If you look at the thread from the
start and realize that we are now arguing about the methodology of
finding the number of months between two dates instead of whether it is
even possible as was originally asserted then I stand proven correct.
There may be different ways to go about it but given a starting date and
a julian number you can indeed calculate whatever element you wish
between the two dates including months (which was not part of my
original assertation but which I'm happy to embrace none-the-less) :)

As an aside it's pretty much a crime to snip your rather beautiful code
to average the months between two dates, I found it enlightening and
have clipped it into my toolbox because I do think there will be points
in the future where that method of date calculation will prove useful,
not in all circumstances of course but I can certainly see where if I
don't need exact matches to real world calendars that it's certainly
better than date averaging!

Thanks for sharing it. I didn't include it here for discussion because
we've wandered outside the scope of the debate into an area which
basically acknowledges that you can indeed get exact answers from
javascript's date object once you define the approach you are going to
use to extract said information.

---------------------------------------------------------------------------
http://www.hunlock.com -- Permanently under construction (And proud of it!)
$FA
Nov 30 '06 #34

P: n/a
In comp.lang.javascript message <s7********************@telcove.net>,
Wed, 29 Nov 2006 13:34:42, Randy Webb <Hi************@aol.comwrote:
>Dr J R Stockton said the following on 11/28/2006 3:36 PM:
>In comp.lang.javascript message <xo********************@telcove.net>,
Tue, 28 Nov 2006 11:50:10, Randy Webb <Hi************@aol.comwrote:
>>>
document.write('example: ' + (+date1));
The ignorant should be unformed that the inner parentheses above are
computationally superfluous.

You should proof read more carefully. I don't expect you to understand
why but the "inner parentheses" are there for a very good reason. And,
they are *not* superfluous. They have a very specific reason for being
there.
> Some may consider that they aid legibility.

Among other reasons. But I didn't add them for legibility.
If you have a good reason you should explain it.

In my system,
document.write('example: ' + (+date1));
document.write('example: ' + +date1);
give identical results.
document.write('example: ' ++date1);

is of course different - but in all the programming languages I know
some whitespace cannot removed without consequences.

Some computationally-superfluous parentheses aid legibility, for some
readers. Authors should know that that pair is optional.

--
(c) John Stockton, Surrey, UK. ??*@merlyn.demon.co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demon.co.uk/- FAQish topics, acronyms, & links.

Food expiry ambiguities: <URL:http://www.merlyn.demon.co.uk/date2k-3.htm#Food>
Nov 30 '06 #35

P: n/a
pcx99 wrote:
In the example we are discussing date1 is a date object. Worse,
it's a smart object. The value it returns depends on how it is used
in javascript.
No it doesn't.
If you say writeln(date1) it's going to return a date string "January
1 2006" or something along that line.
Actually, inside of writeln it is calling toString, which the Date object
defines to return the text string.
If you say writeln(+date1) then it's going to return an integer value that
the date object can convert
back into a string date.
The unary + operator internally calls ToNumber, which internally calls
ToPrimitive with a hint of Number, which internally calls valueOf, which the
Date object defines as returning a number matching getTime().

Context doesn't matter (like it does, for example, in Perl). The internal
conversions of the Date object are what matters.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Nov 30 '06 #36

P: n/a
Matt Kruse wrote:
>If you say writeln(date1) it's going to return a date string "January
1 2006" or something along that line.
Actually, inside of writeln it is calling toString, which the Date
object defines to return the text string.
>If you say writeln(+date1) then it's going to return an integer
value that the date object can convert
back into a string date.
The unary + operator internally calls ToNumber, which internally calls
ToPrimitive with a hint of Number, which internally calls valueOf,
which the Date object defines as returning a number matching
getTime().
Oops, forgot to post the proof that I whipped up:

var d = new Date();
alert(d);
d.toString = function() { return "My date!"; }
alert(d);
alert(+d);
d.valueOf = function() { return 42; }
alert(+d);

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Nov 30 '06 #37

P: n/a
pcx99 said the following on 11/30/2006 12:49 PM:
Arnaud Diederen (aundro) wrote:
>Is the answer there ?
http://www.crockford.com/javascript/jsmin.html

Arnaud


No, though I can see why you would.
Actually, my reason for wrapping it is very much related to that page.

Use any string that can be converted to a number, remove the whitespace
(which is allowed in most JS) and execute it:

myString1 = "123";
myString2 = "456";

alert((+myString1) + (+myString2));
//alerts 579 as expected
alert(+myString1++myString2);
//JS error

The example is simplified but shows the error that can be caused by the
omission of the enclosing parentheses.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Nov 30 '06 #38

P: n/a
Dr J R Stockton said the following on 11/30/2006 6:07 AM:
In comp.lang.javascript message <s7********************@telcove.net>,
Wed, 29 Nov 2006 13:34:42, Randy Webb <Hi************@aol.comwrote:
>Dr J R Stockton said the following on 11/28/2006 3:36 PM:
>>In comp.lang.javascript message <xo********************@telcove.net>,
Tue, 28 Nov 2006 11:50:10, Randy Webb <Hi************@aol.comwrote:
document.write('example: ' + (+date1));
The ignorant should be unformed that the inner parentheses above are
computationally superfluous.
You should proof read more carefully. I don't expect you to understand
why but the "inner parentheses" are there for a very good reason. And,
they are *not* superfluous. They have a very specific reason for being
there.
>> Some may consider that they aid legibility.
Among other reasons. But I didn't add them for legibility.

If you have a good reason you should explain it.
In my system,
document.write('example: ' + (+date1));
document.write('example: ' + +date1);
give identical results.
document.write('example: ' ++date1);

is of course different - but in all the programming languages I know
some whitespace cannot removed without consequences.
Wrap it in parentheses and it can be removed without consequence.
Some computationally-superfluous parentheses aid legibility, for some
readers. Authors should know that that pair is optional.
They are not "computationally-superfluous" nor are they plain
superfluous they are there for a very good reason.

Read my entire answer and the reason becomes obvious.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Nov 30 '06 #39

P: n/a
In comp.lang.javascript message <ek********@news1.newsguy.com>, Thu, 30
Nov 2006 09:49:45, Matt Kruse <ne********@mattkruse.comwrote:
>
Calculating number of months difference for an arbitrary time period (say,
31 days) is impossible without knowing the actual start date.
Strictly, only impossible for Calendar Months (and disregarding Summer
Time). There's an accounting convention of 30-day months - seek DAYS360
in Help of Excel, if available, and maybe elsewhere.

<URL:http://www.merlyn.demon.co.uk/moredate.htm#M30Drefers.
= = = = =

In the unlikely event of anyone using holidays.htm#AW with their own
data-set : Implementing the consequences of yesterday's decision of the
Scottish Parliament, I found a need to deal with a case not previously
encountered - Day Off in a different month. Assuming FTP works, the new
page will have been uploaded by about when you read this.

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v6.05 IE 6.
Web <URL:http://www.merlyn.demon.co.uk/- w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/- see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Nov 30 '06 #40

P: n/a
In comp.lang.javascript message
<JM*****************@newssvr14.news.prodigy.com> , Thu, 30 Nov 2006
04:06:01, pcx99 <x@x.comwrote:
>Dr J R Stockton wrote:
>In comp.lang.javascript message
<7Q***************@newssvr27.news.prodigy.net>, Tue, 28 Nov 2006
10:03:47, pcx99 <x@x.comwrote:
>>Dr J R Stockton wrote:
It is not an arbitrary date; it is a reasonably well-chosen date.

Still arbitrarily set. It could have been 01/01/1969 or 10/25/1955,
from a coding perspective there's no difference between the two.
>Evidently you do not know the proper meaning of Julian Date. Of course,
you are not alone; IBM do not either. Julian Date is a count of days
from Julian Calendar BC 4713-01-01 12:00:00 GMT.

Evidently you're not aware of the function of Julian dates in the
computer sciences. COBOL uses 01/01/1601. NASA uses 5/24/1968.
The PICK OS used 01/01/1965. Astronomers have their own julian system
and there are various other niche systems. These are all Julian date
systems which represents the passage of time with a simple integer.
There is no single Julian date, there is an original Julian calendar
and there are a plethora of additional Julian systems with different
starting dates. The selection of 1/1/1970 was an arbitrary decision by
the developers of the language, 1/2/1970 would have worked just as well
as far as javascript is concerned.

Note that, as a date string, "1/2/1970" is unsatisfactory. Generally it
means 1 Feb 1970, but there are odd places that take it as Jan 2 1970.

There is one internationally defined and accepted Julian date system; it
is that often attributed to Scaliger but actually introduced by the
astronomer John Herschel in 1849. Its zero is Julian BC 4713-01-01
12:00:00 GMT.

COBOL, NASA, etc. use their own daycount systems. NASA does not use
Julian Date; it uses Truncated Julian Date, which is Modified Julian
Date either modulo 10000 or minus 40000. The origin of Pick is
1968-01-01, not 1965-01-01, I gather. Some of them may incorrectly use
the term Julian Date, but that is mere slovenliness.

COBOL actually uses 1600-12-31 as Day Zero. Likewise Pick. But those
who count from 1970-01-01 use that as Day Zero.

>It does not matter for the user's coding.
It DOES matter that you have, either through carelessness or through
lack of understanding, made a false statement which might deceive
innocent readers of your article.

Not. There's no error with the code.
Agreed; I did not say that there was. I said that you made an incorrect
statement. You wrote :-

Assuming you can do that...

var date1 = new Date('21 Nov 2006 09:00:00 PM');
var date2 = new Date('21 Nov 2006 10:00:00 PM');

date1 and date2 now have the total milliseconds since some
arbitrary date back in the 70s. Specifically...

date1: 1,164,164,400,000
date2: 1,164,168,000,000

Those are actually GMT 2006 Nov 22 03:00:00 and 04:00:00; the figures
you give will only be obtained by those who are chronologically retarded
by six hours - Mexico, etc.

>The time zone is simply not a factor in the problem or solution.
>>+ is a concatenation element in javascript and may yield unpredictable
results.
Incorrect. It is an addition operator where both operands are
Number;
if it has a single argument, it yields a Number; if both operands are
Boolean, it coverts them to Number and adds them. If just one argument
is a String, it converts the other to String and concatenates, If both
are strings, it concatenates. Its results are fully defined by
ECMA-262, and I know of no case in which a reputable recent browser gets
it wrong.

This is the relevant part from your quote. This is what I was avoiding
by using multiplication instead of addition...
>>If just one argument
is a String, it converts the other to String and concatenates

The problem is that date1 is not an integer, it is an object. The
multiplication forced it to behave as an integer for the purpose of the
demonstration, however if + is used to force the transformation the
example risked failing because document.writeln('testing: '+date1)
would return a date string and not a date integer which is what I was
discussing.
It is only unary + that is always in effect a to-Number operator. A
binary + often concatenates, but not always - 3+true gives 4.
>I didn't assume the end user would enter the example as entered, I
assumed that while exploring new code the user would expand on the
document.write string for debugging purposes which means using +date1
would yield unpredictable results if the user went from...

document.writeln(+date1); (shows integer value)
to
document.writeln('testing: '+date1); (shows string value, not what we
wanted).
The result is perfectly predictable. The naive user should have
considered what the purpose + may have been, and preserved that effect
by using another + to concatenate.
>By using multiplication in my example, I used javascript's order of
operation to my advantage since multiplication takes priority over
addition (and concatenation) which means that even if the user expands
on my original example, it will still work.

document.writeln('testing: '+date1*1); (still an integer).

Randy Webb correctly noted that

document.writeln('testing: '+(+date1)); (still an integer)
I don't recall that he did, though he would have been correct if he had
done so. He actually wrote

document.writeln('testing: ' + (+date1)); (still an integer)

>would resolve everything to the satisfaction of the great and holy
faqs, but as I said, I deliberately chose multiplication to contain any
chance of concatenation and to simplify the readability of the code for
people learning a new concept.

I think we've all agreed that next time I'll just use date1.getTime()
which will avoid this sort of totally pointless nitpicking.
Date1.valueOf() is better.
>To which I can only conclude you have no understanding of how the
internal julian system works and any further discussion is pointless
until you make an effort to learn it. Suffice it to say that given any
starting date and a julian integer I can calculate the exact
destination date both forward and reverse and any other element you
would like from number of days, weeks, years, even the number of leap
years between the two dates.
I know how the Javascript system works, and I know that Julian Dates,
either in the proper meaning or the IBM meaning, are not involved.
>How do I know this is true? Because to javascript all date/time are
julian integers and from that it calculates the day of the week, the
week of the year,
ECMA Javascript, unaided by extra code, has NO capability for
week-of-the-year. It is possible that some implementations may have
added it. VBScript has it; but the default ignores the International
Standard and the particular case that seems to give ISO numbers gets a
few days wrong.
>and tons of other nifty, useful information regardless of leap years,
and other uncertainties in our real world calendars.
There are no uncertainties in the Gregorian Calendar, apart from how
long it will be used for. There are uncertainties in some
middle-Eastern calendars, but Javascript has nothing for those built-in.
It does all this millions of time every single day, every time
someone does ANYTHING with a date object.
Not strictly true. There are things which one can do with a Date Object
which involve no knowledge of the Calendar or Clock at all. At least
one of them is actually useful - see the FAQ.
>>document.write('example: ' + (+date1));

The ignorant should be unformed that the inner parentheses above are
computationally superfluous. Some may consider that they aid
legibility.


Unformed is right ;) Try taking out the parenthesis around date1 and
seeing how superfluous they really are
The inner parentheses are superfluous. But the two plus signs must not
be consecutive characters.

--
(c) John Stockton, Surrey, UK. ??*@merlyn.demon.co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demon.co.uk/- FAQish topics, acronyms, & links.
Check boilerplate spelling -- error is a public sign of incompetence.
Never fully trust an article from a poster who gives no full real name.
Nov 30 '06 #41

P: n/a
Matt Kruse wrote:
How would you resolve it to a fraction of a month, when you don't really
know how long a "month" is?

IMO, the logical way to compute a datediff for period month is to see how
many month changes happen between two dates. So the number of months between
Jan 31 and Feb 1 is 1, because one month change has happened.

Calculating number of months difference for an arbitrary time period (say,
31 days) is impossible without knowing the actual start date.
In my experience, the way to calculate how many months between two dates
is depending on the business requirement and for me just to fit their
requirement. It is easy.

For example, there is a business requirement from user that the practice
is to have how many days between two dates first and divide it into 30
days, then always Math.ceil().

Dec 1 '06 #42

P: n/a
In comp.lang.javascript message <pq********************@telcove.net>,
Thu, 30 Nov 2006 16:41:31, Randy Webb <Hi************@aol.comwrote:
>pcx99 said the following on 11/30/2006 12:49 PM:
>Arnaud Diederen (aundro) wrote:
>>Is the answer there ?
http://www.crockford.com/javascript/jsmin.html

Arnaud
No, though I can see why you would.

Actually, my reason for wrapping it is very much related to that page.

Use any string that can be converted to a number, remove the whitespace
(which is allowed in most JS) and execute it:

myString1 = "123";
myString2 = "456";

alert((+myString1) + (+myString2));
//alerts 579 as expected
alert(+myString1++myString2);
//JS error

The example is simplified but shows the error that can be caused by the
omission of the enclosing parentheses.

It does not. It shows that omitting the enclosing parentheses AND ALSO
removing two spaces is wrong.

There are other cases where a space must not be removed :
do X=3;while(false)
case 99:
break Fred
return Ticket
new Date()

Removing one of the spaces as well as the parentheses changes the
statement from holding two + tokens to holding one ++ token.

Those parentheses may provide idiot-proofing; but a
correctly-implemented Javascript engine, while sometimes seeming
perverse, is not an idiot.

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demon.co.uk/- FAQish topics, acronyms, & links.
Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "" (SonOfRFC1036)
Dec 1 '06 #43

P: n/a
pcx99 wrote:
Dr J R Stockton wrote:
>In comp.lang.javascript message
<7Q***************@newssvr27.news.prodigy.net>, Tue, 28 Nov 2006
10:03:47, pcx99 <x@x.comwrote:
>>Dr J R Stockton wrote:
It is not an arbitrary date; it is a reasonably well-chosen date.

Still arbitrarily set. It could have been 01/01/1969 or 10/25/1955,
from a coding perspective there's no difference between the two.
>Evidently you do not know the proper meaning of Julian Date. Of course,
you are not alone; IBM do not either. Julian Date is a count of days
from Julian Calendar BC 4713-01-01 12:00:00 GMT.

Evidently you're not aware of the function of Julian dates in the
computer sciences. COBOL uses 01/01/1601. NASA uses 5/24/1968. The
PICK OS used 01/01/1965. Astronomers have their own julian system and
there are various other niche systems. These are all Julian date
systems which represents the passage of time with a simple integer.
There is no single Julian date, there is an original Julian calendar and
there are a plethora of additional Julian systems with different
starting dates. The selection of 1/1/1970 was an arbitrary decision by
the developers of the language, 1/2/1970 would have worked just as well
as far as javascript is concerned.
The Julian date and the Julian calendar are unrelated; they were
accidentally both named in honor of two different men named "Julius".

The genuine Julian date starts January 1st, 4713 B.C. The other "Julian
dates" are bastard usages invented by illiterates to spread confusion
and havoc.

--
John W. Kennedy
"The blind rulers of Logres
Nourished the land on a fallacy of rational virtue."
-- Charles Williams. "Taliessin through Logres: Prelude"
Dec 2 '06 #44

P: n/a
In comp.lang.javascript message <Od***************@newsfe11.lga>, Sat, 2
Dec 2006 00:32:26, John W. Kennedy <jw*****@attglobal.netwrote:
>
The Julian date and the Julian calendar are unrelated; they were
accidentally both named in honor of two different men named "Julius".
The Julian Calendar was undoubtedly named after the one who decreed it,
the real-life version of the well-known Shakespeare character, though I
don't know who actually decided to call it that. Perhaps Sosigenes was
told to do so.

The Julian Period was undoubtedly invented by Scaliger /fils/ and named
by him after Scaliger /pere/.

The use of Julian Date was invented by John Herschel, and its origin is
the beginning of Scaliger's Julian Period. But is it known who *named*
it "Julian" (probably Herschel, though he had a perfectly good /pere/
who he could have honoured) and for certain whether the Julian is in
fact Scaliger's dad or is some other worthy, presumably not Caesar?

>The genuine Julian date starts January 1st, 4713 B.C. The other "Julian
dates" are bastard usages invented by illiterates to spread confusion
and havoc.
The Chronological Julian Date starts then, Julian BC 4713-01-01 00:00:00
local time being Date 0.0.

The Julian Date starts at Julian BC 4713-01-01 12:00:00 GMT being Date
0.0.

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v6.05 IE 6.
Web <URL:http://www.merlyn.demon.co.uk/- w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/- see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Dec 2 '06 #45

This discussion thread is closed

Replies have been disabled for this discussion.