473,651 Members | 2,792 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem with count-up script

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=Javasc ript type=text/javascript class="smalltex t">
/*

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 bh*****@indyuni x.iupui.edu 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.getFullYe ar()
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)

premonthssincet wo = (premonthssince + 1)

else premonthssincet wo = (premonthssince )

if (premonthssince two == 0)

monthssince = (" ")

else if (premonthssince two == 1)

monthssince = ("0 months")

else monthssince = (premonthssince two +
" 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!
----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 23 '05 #1
20 2958
VK

no**@of.your.bi z.nes wrote:
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).

Nov 23 '05 #2
no**@of.your.bi z.nes wrote:
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:

<URL:http://www.merlyn.demo n.co.uk/js-dates.htm>


=== Cut ===
<script language=Javasc ript type=text/javascript class="smalltex t">
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:

<script type="text/javascript">


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.getFullYe ar()
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.getFullYe ar();
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.getFullY ear()*12 + toDate.getMonth ();
var fromMonths = fromDate.getFul lYear()*12 + fromDate.getMon th();

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

// Subtract months from toDate months, fix if goes too far
toDate.setMonth (toDate.getMont h() - months);
if (toDate < fromDate) {
toDate.setMonth (toDate.getMont h()+1);
--months;
}
// Calc whole years and months
var years = Math.floor(mont hs/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(dateDifYM D('1994-10-15'));
[...]
--
Rob
Nov 23 '05 #3
VK

no**@of.your.bi z.nes wrote:
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.

Nov 23 '05 #4
RobG wrote:
no**@of.your.bi z.nes wrote:
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.getFullY ear()*12 + toDate.getMonth ();
var fromMonths = fromDate.getFul lYear()*12 + fromDate.getMon th();

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

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

// Add days one by one until gone too far
var days=0;
while (fromDate < toDate) {
fromDate.setDat e(fromDate.getD ate()+1);
++days;
}
// Adjust for going too far
--days;
var X = { addS : function(n){ret urn (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(dateDifYM D('1994-10-15'));
--
Rob
Nov 23 '05 #5
JRS: In article <11************ *********@g14g2 000cwa.googlegr oups.com>,
dated Sat, 19 Nov 2005 11:51:25, seen in news:comp.lang. javascript, VK
<sc**********@y ahoo.com> posted :

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.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demo n.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demo n.co.uk/programs/> - see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Nov 23 '05 #6
JRS: In article <Go************ *************** *@of.your.biz.n es>, dated
Sat, 19 Nov 2005 13:41:36, seen in news:comp.lang. javascript,
no**@of.your.bi z.nes <DA************ ******@your.bis .nes> posted :
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=Javasc ript type=text/javascript class="smalltex t">
/*

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 bh*****@indyuni x.iupui.edu 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.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Nov 23 '05 #7

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('199 4-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
----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 23 '05 #8
Dr John Stockton said the following on 11/20/2005 5:00 PM:

<snip>
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.

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Nov 23 '05 #9

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

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
2219
by: Christopher Brandsdal | last post by:
Hi! I have a problem running my code on 2000 server and iis5.0. The code runs perfectly on my localhost (xp iis5.1) but when i run it on 2000 server iis5.0 I get this error: -------------------------------------- operation must use an updateable query
1
1261
by: sajidazmi | last post by:
Hi, I'm coding an Stock Order Entry System. The problem I'm facing is when I'm passing a pointer to one class, the pointer gets corrupted. I'm not able to see why? Here is the code, please tell me what I'm doing wrong. Problem are marked as <== in the code. /** Class Header **/ /* * Symbol
8
1979
by: Sowen | last post by:
Hi, I have an object "elem", there are only simple functions inside, like setName, getName, and three constructors Now I have another class "Base", need an array of elem to initialize class Base { public:
1
4234
by: Rohit Raghuwanshi | last post by:
Hello all, we are running a delphi application with DB2 V8.01 which is causing deadlocks when rows are being inserted into a table. Attaching the Event Monitor Log (DEADLOCKS WITH DETAILS) here. From the log it looks like the problem happens when 2 threads insert 1 record each in the same table and then try to aquire a NS (Next Key Share) lock on the record inserterd by the other thread. Thanks Rohit
4
1736
by: Jeffrey Barrett | last post by:
Can someone tell me why I'm having this problem: When I select drink 5 and deposit too little money, there's a problem with the 'difference' variable. Try to deposit $.80 instead of the full $.85 and see what happens if you then keep entering .01 until you have added the full .85. The program still asks the user to deposit $0.00. It is telling me for some reason that 0.850000 - 0.850000 = 5.96046e-008. Any suggestions? /*
2
5325
by: Tony O'Bryan | last post by:
I am normally the admin for our PostgreSQL servers, but someone else tried to kill a runaway query while I was out sick. Unfortunately, he tried killing the runaway query by killing the postmaster. Now we are dealing with a persistent problem that just won't go away. 1) Spontaneous back end deaths. 2) Spontaneous backend disconnects (which are probably because of 1). 3) pg_clog files disappearing. The first symptom of the problem...
4
7139
by: MrL8Knight | last post by:
Hello, I am trying to build a simple php form based shopping cart using a cookie with arrays. I need to use 1 cookie because each order will have over 20 items. With that said, I realize I need to serialize the data to put the array into the cookie. That part of my code is working just fine and displaying fine. The problem I’m having is when I try to unserialize and display; the data does not appear. If I remove my unserialize command line (see...
52
5369
by: celerysoup16 | last post by:
I've written this coin toss program, and can't figure out why it isn't giving accurate results... cheers, Ben #include <stdlib.h> #include <stdio.h> #define H 1 #define T 0 #define SENTINEL -1
22
12462
by: MP | last post by:
vb6,ado,mdb,win2k i pass the sql string to the .Execute method on the open connection to Table_Name(const) db table fwiw (the connection opened via class wrapper:) msConnString = "Data Source=" & msDbFilename moConn.Properties("Persist Security Info") = False moConn.ConnectionString = msConnString moConn.CursorLocation = adUseClient moConn.Mode = adModeReadWrite' or using default...same result
5
1718
by: Chad | last post by:
say my input file is $ more suck ______ < gnu? > ------ \ , , \ /( )` \ \ \___ / | /- _ `-/ '
0
8352
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8802
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8697
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8465
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7297
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5612
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4144
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4283
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1587
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.