Problem with count-up script

N

none

I have managed to get the below script *almost* working. However, it
still has a problem calculating the number of months. The date I am
trying to calculate from is Oct 15, 1994. With the correct "thatmonth"
(10) it displays 0. With 9 it displays 2, instead of 1 which would be
correct.

Any suggestions?

=== Cut ===
<script language=Javascript type=text/javascript class="smalltext">
/*

Date Count-up 1.0
(C) Copyright 1996 Ben Harold
All rights Reserved
Feel free to use this script in your page under the folling
conditions :
1. Do not modify this script in any way (besides
following the
configuration directions) without my consent
2. Mail me at (e-mail address removed) if you use it
3. I am not held responsible for any thing that this
script may
do to your computer
*/

// Configuration Directions
// Don't change this
// This makes a date variable that is used to get the current date

today = new Date()

// Don't change these
// These get the current year, month, and date

var thisyear = today.getFullYear()
var thismonth = today.getMonth()
var thisdate = today.getDate()

// Change these
// These set the year, month, and date to count from
// NOTICE : var thatmonth should be a number between 0 and 11, not 1
and 12

var thatyear = 1994
var thatmonth = 9
var thatdate = 15

// Change this
// This is what the browser will display just before the years, months,
and dates
// NOTICE : make sure that there is a space after the last word of var
prestring

var prestring = " "

// Don't change these
// These set variables used by other parts of the script

var fromyears = (thisyear - thatyear)
var datenumber = (thisdate + thatdate)

// Don't change this
// This figures out how many days there are in the current month


if (thismonth == 0)

monthdates = (31)

else if (thismonth == 1)

monthdates = (28)

else if (thismonth == 2)

monthdates = (31)

else if (thismonth == 3)

monthdates = (30)

else if (thismonth == 4)

monthdates = (31)

else if (thismonth == 5)

monthdates = (30)

else if (thismonth == 6)

monthdates = (31)

else if (thismonth == 7)

monthdates = (31)

else if (thismonth == 8)

monthdates = (30)

else if (thismonth == 9)

monthdates = (31)

else if (thismonth == 10)

monthdates = (30)

else if (thismonth == 11)

monthdates = (31)



// Don't change this
// This figures out how many years it has been since thatyear


if (fromyears == 0)

yearssince = (prestring)

else if (fromyears == 1)

yearssince = (prestring + " year")

else yearssince = (prestring + fromyears + " years")


// Don't change this
// This figures out how many dates it has been since thatdate


if (thisdate > thatdate)

predatessince = (thisdate - thatdate)

else predatessince = (thisdate + monthdates - thatdate)

if (predatessince == 0)

datessince = ("no days.")

else if (predatessince == 1)

datessince = ("1 day.")

else datessince = (predatessince + " days.")

// Don't change this
// This figures out how many months it has been since thatmonth


if (thisyear > thatyear) {

if (thismonth >= thatmonth)

premonthssince = (thismonth -
thatmonth)

else premonthssince = (12 + thismonth -
thatmonth)

}

else premonthssince = (thismonth - thatmonth)

if (monthdates < datenumber)

premonthssincetwo = (premonthssince + 1)

else premonthssincetwo = (premonthssince)

if (premonthssincetwo == 0)

monthssince = (" ")

else if (premonthssincetwo == 1)

monthssince = ("0 months")

else monthssince = (premonthssincetwo +
" months")


// Don't change these
// These figure out what type of punctuation to use in the final
message


if (yearssince == prestring)

commaone = (" ")

else {

if (monthssince == " ")

(commaone = " and ")

else commaone = (", ")

}


if (commaone == " and ")

commatwo = (" ")

else if (commaone == ", ")

commatwo = (" and ")

else if (yearssince == prestring) {

if (monthssince == " ")

(commatwo = " ")

else commatwo = (" and ")

}


// Don't change this
// This assembles the final message


var finalstring = ""

finalstring += (yearssince)

finalstring += (commaone)

finalstring += (monthssince)

finalstring += (commatwo)

finalstring += (datessince)


// Don't change this
// This prints the final message to the browser screen


document.write(finalstring)

</script>
=== Cut ===


Kari Suomela

KARICO Business Services
Toronto, ON Canada
http://www.karico.ca

.... Next - condemning motherhood and apple pie - Geraldo!
 
V

VK

I have managed to get the below script *almost* working. However, it
still has a problem calculating the number of months. The date I am
trying to calculate from is Oct 15, 1994. With the correct "thatmonth"
(10) it displays 0. With 9 it displays 2, instead of 1 which would be
correct.

I'm sorry, I tried to help for around 10 mins but this scripting is so
strange, I just couldn't follow it anymore. It's like Him Who Want To
Kill The Programming wrote it himself, I just feel some evil force
comimg out from the lines :)
Sorry, sorry, sorry if it's your script.

Two errors I managed to notice before the darkness in my eyes:

[1] It is presumed that February contains 28 days only. It is not
exactly true. It contains 28 days in regular year and 29 days in so
called leap year. The common formula for leap year (accounting also the
often forgotten "odd on 400" rule) returns true if leap year, false
otherwise:

function isLeap(year) {
if ((year%400==0)||((year%4==0)&&(year%100!=0))) {return true;}
else {return false;}}

[2] daythis+daythat may give you an interesting result for say 15 and
17 (32 October or so).
 
R

RobG

I have managed to get the below script *almost* working. However, it
still has a problem calculating the number of months. The date I am
trying to calculate from is Oct 15, 1994. With the correct "thatmonth"
(10) it displays 0. With 9 it displays 2, instead of 1 which would be
correct.

Any suggestions?

You seem to have determined to go about this the longest way possible.
If your intention is to count the number of days, months and years since
15 October, 1994 (someone's birthday?) then there are much more
concise ways of doing it.

You will find lots of stuff about date arithmetic here:

=== Cut ===
<script language=Javascript type=text/javascript class="smalltext">

There seems little point in giving a script element a class. The
language attribute is deprecated, keep type, and it is always a good
idea to quote attribute values even when not needed:

Date Count-up 1.0
(C) Copyright 1996 Ben Harold

I've seem similar stuff to this posted elsewhere, I don't know if it was
Ben's work but the algorithm was just as long and painful.

[...]
today = new Date()

That creates a global variable which is just not necessary. Keep it
local with 'var':

var today = new Date();
var thisyear = today.getFullYear()
var thismonth = today.getMonth()
var thisdate = today.getDate()

Statements should be terminated with a semi-colon. The interpreter will
insert them where it thinks they should go, but why leave it to chance?

var thisyear = today.getFullYear();
var thismonth = today.getMonth();
var thisdate = today.getDate();
var thatyear = 1994
var thatmonth = 9
var thatdate = 15
var prestring = " "


var fromyears = (thisyear - thatyear)
var datenumber = (thisdate + thatdate)

// Don't change this
// This figures out how many days there are in the current month

A much more concise routine is to set a date of a date object to the 0th
of next month, then get its date. Since you already have the number of
this month and the year:

var monthdates = new Date(thisyear,(thismonth + 1),0).getDate();


And you're done.

But rather than mess with that, here's a routine that will do what you
want, it isn't optimal for speed and needs the 'fromDate' to be earlier
than the 'toDate'. Daylight saving should not be an issue and if your
system date is wrong... well, I can't fix that from here. :)

It could also be more concise, but it should do the job.


// Pass a date string with format YYYY-MM-DD,
// e.g. '1994-10-15'
function dateDifYMD(ds){
// Create from and to date objects - from must be earlier date
var toDate = new Date();
var dsA = ds.split('-');
var fromDate = new Date(+dsA[0], +dsA[1]-1, +dsA[2]);

// Get month counts for both dates
var toMonths = toDate.getFullYear()*12 + toDate.getMonth();
var fromMonths = fromDate.getFullYear()*12 + fromDate.getMonth();

// Get difference in months
var months = toMonths - fromMonths;

// Subtract months from toDate months, fix if goes too far
toDate.setMonth(toDate.getMonth() - months);
if (toDate < fromDate) {
toDate.setMonth(toDate.getMonth()+1);
--months;
}
// Calc whole years and months
var years = Math.floor(months/12);
months = months%12; // or months = months - years*12;

// Subtract days one by one until gone too far
var days=0;
while (toDate > fromDate) {
toDate.setDate(toDate.getDate()-1);
++days;
}
// Adjust for going too far
--days;

// Format return string
var rString = years + 'year' + ((years != 1)?'s':'') + ', '
+ months + 'month' + ((months != 1)?'s':'') + ', '
+ days + 'day' + ((days != 1)?'s':'');

return rString;
}

alert(dateDifYMD('1994-10-15'));


[...]
 
V

VK

I have managed to get the below script *almost* working. However, it
still has a problem calculating the number of months. The date I am
trying to calculate from is Oct 15, 1994. With the correct "thatmonth"
(10) it displays 0. With 9 it displays 2, instead of 1 which would be
correct.

Besides the great help RobG provided to you, I wanted to tell you that
I tried to write a script for you too as I felt obligated after my
initial (though explicable) reaction.

But few minutes later I realized that this task *doesn't have an exact
mathematical solution*. It is a trivia to calculate the amount of
milliseconds between two dates. So it's a trivia to calculate the
amount of seconds, minutes, hours and days.

But you cannot say "where are exactly X years, Y months and Z days
since then".

X of what years? Standard, leap, 3 standard + 1 leap ?
Y of what month? Consisting of 30 days, 29 days, 30+31 pairs?

So the only *calculatable* answer can be: "where are Z days since
then".

P.S. Unless I'm missing something and there are some common
international agreements about this.
 
R

RobG

RobG said:
I have managed to get the below script *almost* working. However, it
still has a problem calculating the number of months. The date I am
trying to calculate from is Oct 15, 1994. With the correct "thatmonth"
(10) it displays 0. With 9 it displays 2, instead of 1 which would be
correct.

Any suggestions?
[...]
But rather than mess with that, here's a routine that will do what you
want, it isn't optimal for speed and needs the 'fromDate' to be earlier
than the 'toDate'. Daylight saving should not be an issue and if your
system date is wrong... well, I can't fix that from here. :)

Seems I mixed counting forward and backward, which isn't good. Here's
a modified script that only counts forward, which seems more inline
with what you want.


// Pass a date string with format YYYY-MM-DD
// e.g. '1994-10-15'
// Date must be today or earlier
function dateDifYMD(ds){
// Create from and to date objects - from must be earlier date
var toDate = new Date();
var dsA = ds.split('-');
var fromDate = new Date(+dsA[0], +dsA[1]-1, +dsA[2]);

// Get month counts for both dates
var toMonths = toDate.getFullYear()*12 + toDate.getMonth();
var fromMonths = fromDate.getFullYear()*12 + fromDate.getMonth();

// Get difference in months
var months = toMonths - fromMonths;

// Add months to fromDate, fix if goes too far
fromDate.setMonth(fromDate.getMonth() + months);
if (fromDate > toDate) {
fromDate.setMonth(fromDate.getMonth()-1);
--months;
}
// Calc whole years and months
var years = Math.floor(months/12);
months = months%12; // or months -= years*12;

// Add days one by one until gone too far
var days=0;
while (fromDate < toDate) {
fromDate.setDate(fromDate.getDate()+1);
++days;
}
// Adjust for going too far
--days;


var X = { addS : function(n){return (n==1)? '':'s';}};

// Format return string
var rString = years + 'year' + X.addS(years) + ', '
+ months + 'month' + X.addS(months) + ', '
+ days + 'day' + X.addS(days);

return rString;
}

alert(dateDifYMD('1994-10-15'));
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated
Sat, 19 Nov 2005 13:41:36, seen in
I have managed to get the below script *almost* working. However, it
still has a problem calculating the number of months. The date I am
trying to calculate from is Oct 15, 1994. With the correct "thatmonth"
(10) it displays 0. With 9 it displays 2, instead of 1 which would be
correct.

Any suggestions?

=== Cut ===
<script language=Javascript type=text/javascript class="smalltext">
/*

Date Count-up 1.0
(C) Copyright 1996 Ben Harold
All rights Reserved
Feel free to use this script in your page under the folling
conditions :
1. Do not modify this script in any way (besides
following the
configuration directions) without my consent
2. Mail me at (e-mail address removed) if you use it
3. I am not held responsible for any thing that this
script may
do to your computer
*/

Since the material is copyright, you are not entitled to post it here.

You are explicitly not allowed to modify it, except to alter the given
date.

Since the author appears semi-literate, one should assume that his code
may well be of low standard.

That can be confirmed by reading the code.
Kari Suomela

KARICO Business Services
Toronto, ON Canada
http://www.karico.ca



The second thing you need to learn is how to discriminate between code
that is worth using and code that is not. Read the newsgroup FAQ; see
below.
 
D

Dr John Stockton

JRS: In article <[email protected]>,
dated Sat, 19 Nov 2005 11:51:25, seen in VK
function isLeap(year) {
if ((year%400==0)||((year%4==0)&&(year%100!=0))) {return true;}
else {return false;}}

Granted that the difference will not be noticeable; but a thoughtful
programmer would do the tests in the order 4, 100, 400, and would
arrange that the process would not do more tests than are really
necessary.

If you are asked whether the Gregorian year 12345678 will be Leap,
surely you won't first test divisibility by 400?


if (cond) {return true;}
else {return false;}
is amateurish; a sign of an inadequate education.
return cond;
is all that is needed, if cond is already Boolean; otherwise
return !!cond;


To determine the length of month M (1..12) of year Y there's no need to
code a Leap Year algorithm.
LofM = new Date(Y, M, 0).getDate() ;
LofM = new Date(Date.UTC(Y, M, 0)).getUTCDate() ;
or one of the efficient methods discussed here a while back.

It appears that you have not yet read the newsgroup FAQ.
 
N

none

Sunday November 20 2005 23:44, RobG wrote to All:


R> // Format return string
R> var rString = years + 'year' + X.addS(years) + ', '
R> + months + 'month' + X.addS(months) + ', '
R> + days + 'day' + X.addS(days);

R> return rString;

Thank you. Now we have the return values correct. I want it to display
on the page, so I changed the last line to:


document.write(dateDifYMD('1994-10-15'));

Now, if I'd get a space between the number and 'month' etc., I could go
back to babysitting my grandkids. ;)


Kari Suomela

KARICO Business Services
Toronto, ON Canada
http://www.karico.ca
 
R

Randy Webb

Dr John Stockton said the following on 11/20/2005 5:00 PM:

if (cond) {return true;}
else {return false;}
is amateurish; a sign of an inadequate education.

That is total 100% nonsense. When teaching a newbe, it is best to keep
it simple and let them learn the shortcuts on there own. By showing the
full steps, it helps in that education, not hinders it.
 
N

none

Sunday November 20 2005 21:33, Dr John Stockton wrote to All:


DS> The second thing you need to learn is how to discriminate between
DS> code
DS> that is worth using and code that is not. Read the newsgroup FAQ;
DS> see
DS> below.

Gee! That sure sounds constructive and helpful! If you don't know the
answer, why bother posting - Mr Doc?!

KS
 
L

Lee

Randy Webb said:
Dr John Stockton said the following on 11/20/2005 5:00 PM:



That is total 100% nonsense. When teaching a newbe, it is best to keep
it simple and let them learn the shortcuts on there own. By showing the
full steps, it helps in that education, not hinders it.

But the "full steps" in this case are:

return (cond);

That isn't a shortcut. Anything more is going out of your way to
write extra code, which is not something I would want to teach.
 
R

RobG

Sunday November 20 2005 23:44, RobG wrote to All:


R> // Format return string
R> var rString = years + 'year' + X.addS(years) + ', '
R> + months + 'month' + X.addS(months) + ', '
R> + days + 'day' + X.addS(days);

R> return rString;

Thank you. Now we have the return values correct. I want it to display
on the page, so I changed the last line to:


document.write(dateDifYMD('1994-10-15'));

Now, if I'd get a space between the number and 'month' etc., I could go
back to babysitting my grandkids. ;)

Insert them into strings wherever you want:

var rString = years + ' year' + X.addS(years) + ', '
//---------------------------^

and so on. Say 'hi' to the kids :)
 
N

none

Monday November 21 2005 06:14, RobG wrote to All:


R> Insert them into strings wherever you want:

R> var rString = years + ' year' + X.addS(years) + ', '
R> //---------------------------^

R> and so on. Say 'hi' to the kids :)


Thx. They asked to say hello to you, too. ;)

KS
 
D

Dr John Stockton

JRS: In article <[email protected]>
, dated Sat, 19 Nov 2005 18:11:44, seen in VK
But few minutes later I realized that this task *doesn't have an exact
mathematical solution*. It is a trivia to calculate the amount of
milliseconds between two dates. So it's a trivia to calculate the
amount of seconds, minutes, hours and days.

But you cannot say "where are exactly X years, Y months and Z days
since then".

X of what years? Standard, leap, 3 standard + 1 leap ?
Y of what month? Consisting of 30 days, 29 days, 30+31 pairs?

So the only *calculatable* answer can be: "where are Z days since
then".

P.S. Unless I'm missing something and there are some common
international agreements about this.

Well, you are, of course. Read the newsgroup FAQ.

There's a standard for the use of 30-day months used internationally at
least in Europe. The Americans have a different one, of course.

Then it's certainly possible to count forward in exact years from the
start date, without going too far; then exact months, without, then days
- in that, "exact" means by adding one to the number, and some rule for
stopping on a too-short month is needed.

Another way would be to determine the difference in days, divide by
365.25/12 or 365.2425/12 and round down to get integer months, after
which the rest is trivial. However, it makes the effects of varying
month- and year- lengths rather conspicuous.

It's not a useful thing to calculate, except as an exercise.
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Sun, 20 Nov
2005 19:36:56, seen in Randy Webb
Dr John Stockton said the following on 11/20/2005 5:00 PM:



That is total 100% nonsense. When teaching a newbe, it is best to keep
it simple and let them learn the shortcuts on there own. By showing the
full steps, it helps in that education, not hinders it.

It is important to teach how to do things properly. That includes
teaching an understanding of Booleans. Don't try to dumb everybody down
to what you consider reasonable.
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated
Sun, 20 Nov 2005 21:39:46, seen in
Sunday November 20 2005 21:33, Dr John Stockton wrote to All:


DS> The second thing you need to learn is how to discriminate between
DS> code
DS> that is worth using and code that is not. Read the newsgroup FAQ;
DS> see
DS> below.

Gee! That sure sounds constructive and helpful! If you don't know the
answer, why bother posting - Mr Doc?!

To point out that you are a thief, but without the intelligence to
choose to steal something worth having and usable by yourself.

And to tell you what you need to learn about re-use of code; and to tell
you how to find the other information that you need, though you do not
deserve that.

But I can give you further information; your service provider includes
in your article headers the following :

X-Report: Please report illegal or inappropriate use to
<[email protected]>. Forward a copy of ALL headers INCLUDING the body.
(DO NOT SEND ATTACHMENTS)
X-Comments2: IMPORTANT: Newsfeeds.com does not condone,support,nor
tolerate spam or any illegal or copyrighted postings.
X-Comments: This message was posted through Newsfeeds.com

So your action is specifically forbidden by your provider.


<FAQENTRY> Section 2 - Don't post copyright material, including mail,
without permission.
 
R

Randy Webb

Dr John Stockton said the following on 11/22/2005 8:06 AM:
JRS: In article <[email protected]>, dated Sun, 20 Nov
2005 19:36:56, seen in Randy Webb



It is important to teach how to do things properly. That includes
teaching an understanding of Booleans.

It also includes teaching the basics of an if/else statement. Teach the
basics, then move on to the Booleans. Don't just straight to the Moon
from the lab.
Don't try to dumb everybody down to what you consider reasonable.

That is so idiotic that it doesn't deserve a reply. Nothing I said even
came remotely close to implying to "dumb people down". Stick to Numbers
John, your pedantic insults get old.
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated
Thu, 24 Nov 2005 00:04:20, seen in Randy Webb
Dr John Stockton said the following on 11/22/2005 8:06 AM:

It also includes teaching the basics of an if/else statement. Teach the
basics, then move on to the Booleans. Don't just straight to the Moon
from the lab.

Don't try to teach with bad examples; it's easy enough to find good
ones. Booleans are in fact more basic than if (cond) then else, because
cond is itself a Boolean.

An example such as that - even when presented by VK - may well confuse a
programmer new to javascript into thinking that it, unlike other
languages he's learned, does not have true Booleans.
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Wed, 23
Nov 2005 05:49:17, seen in Jasen Betts
In australia they are 4-1/3 weeks.
when paying rent monthly, it's 4-1/3 times the weekly amount


Interesting, noted. That gives a discount of about 1.25 parts in 365.25
for paying less often.
 

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

Similar Threads


Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top