PDA

View Full Version : Need Date Script Help



SunKiss
09-14-2006, 08:21 PM
I'm trying to calculate "Days Till" with 2 input fields, one for start date and one for number of days till. I've got something wrong. Here is the code I'm working with the way I have it set up currently:

<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<BODY>

<SCRIPT Language="JavaScript">
function CalcNow()

var today = new Date()
var targetDate = new Date(document.forms.form1.datea.value) //use full year
var timeBeforeTarget = Math.floor(( targetDate.getTime()
- today.getTime()) / 86400000)
var msg = (timeBeforeTarget +1)

document.forms.form1.output = (msg)
//-->
</SCRIPT>
<form name="form1" method="post" action="">
<p>
<input name="datea" type="text" id="datea">
</p>
<p>
<input name="output" type="text" onfocus="CalcNow(this.form);"id="output">
</p>
</form>
</body>
</html>


Here is the original script:

<SCRIPT Language="JavaScript">
<!-- hide from old browsers
var today = new Date()
var targetDate = new Date("01/01/3000") //use full year
var timeBeforeTarget = Math.floor(( targetDate.getTime()
- today.getTime()) / 86400000)
var msg = "<B>There are only " + (timeBeforeTarget +1)
+ " days until the year 3000.</B>"
document.write(msg)
//-->
</SCRIPT>


Any help is appreciated.

tech_support
09-15-2006, 12:55 AM
Like this? http://www.dynamicdrive.com/dynamicindex6/dhtmlcount.htm

blm126
09-15-2006, 01:06 AM
My guess, is that these lines are causing problems


var timeBeforeTarget = Math.floor(( targetDate.getTime()
- today.getTime()) / 86400000)

This should be written as


var timeBeforeTarget = Math.floor(( targetDate.getTime() - today.getTime()) / 86400000)

white space makes a difference in javascript

mwinter
09-15-2006, 01:46 AM
<body>
<BODY>

Two start-tags? :)



<SCRIPT Language="JavaScript">

The language attribute has been deprecated for a very long time. Use the type attribute:



<script type="text/javascript">



function CalcNow()

Your biggest immediate problem is that you've missed the (required) braces in the function definition.

An oddity is that you (try to) call this function with a reference to the form, but you don't include a formal argument, nor use that reference in the function itself. It would make referencing controls easier if you did.



var today = new Date()

One should get into the habit of using semicolons to terminate statements.



var targetDate = new Date(document.forms.form1.datea.value) //use full year

It's probably not a good idea to pass user input directly to the Date constructor function. It would be better to first verify that it's in a sensible format (yyyy-mm-dd, preferably), then pass each component as a number to the constructor, and finally check that the values didn't cause a rollover (which would indicate out-of-bounds values).



var timeBeforeTarget = Math.floor(( targetDate.getTime()
- today.getTime()) / 86400000)

Rounding, rather than truncating, might be better with regard to daylight savings.



var msg = (timeBeforeTarget +1)

Those parentheses are unnecessary.



document.forms.form1.output = (msg)

Same here.



//-->

That should be there at all.

I should be asleep right now, so I'm not going to post an alternative yet, but someone else might before I get around to it.






var timeBeforeTarget = Math.floor(( targetDate.getTime()
- today.getTime()) / 86400000)


This should be written as


var timeBeforeTarget = Math.floor(( targetDate.getTime() - today.getTime()) / 86400000)

white space makes a difference in javascript

Not here. Breaking lines between tokens is fine, though there are a few restricted productions (namely post-increment and -decrement operators and the return, continue, break, and throw statements) where line breaks are controlled (but not completely disallowed):



number
++; /* wrong */

number ++; /* right */

return
expression + another; /* wrong */

return expression
+ another; /* right */

Mike

SunKiss
09-15-2006, 12:49 PM
Hi Mike and everyone else,
Thanks for your feedback. I'm looking forward to seeing your alternative.

It goes without saying that I'm very much in the learning stages of JS. The biggest problem I've had is finding examples that explain adaquately how to deal with form input, etc. and the logic and syntax for coding. The code I posted is a prime example. I've found plenty of count down scripts, or "days till date" scripts, as well as tutorials on various ways to do it, but every one of the examples and tutorials assume that we are always going to be dealing with a static date with print out to another page. None of them explain how to reference a user input field and process the difference between the input date and the current date and output the result to a form field on the same page.

Thanks Mike, for taking the time to explain a lot more about what's going on. I still don't follow all of what you've pointed out.

What braces in function did I leave out?
Can you give an example of the formal argument? How should it be in the form and function?

You said:


Can you give an example or further explain how you would deal with this? Perhaps some code or reference to a code snippet?

Do you mean that statements like:

var today = new Date()
should end with a semicolon like this?

var today = new Date();

Thanks for letting me know about the parentheses. Also thanks for keeping me straight on the line break. I would have really been confused.

I've tried several variations of this code, playing around with it trying to get it to work and trying to understand it at the same time so I may have actually done some of the things you've said, probably just not all the right ones at the same time.

I await your next post!!
Mark

SunKiss
09-16-2006, 11:38 AM
The following is a portion of a script I have and I need to modify it. It currently uses 2 input boxes to determine the difference between 2 dates but I need it to determine the difference between the "Current Date" (today's date) and 1 input date. I believe this is the portion of the script that does this function. How can I modify it to use "Current Date" in place of one input box?

function dateDiff(charges) {
date1 = new Date();
date2 = new Date();
diff = new Date();

if (isValidDate(charges.date8a.value) && isValidTime(charges.firsttime.value)) { // Validates first date
date1temp = new Date(charges.date8a.value + " " + charges.firsttime.value);
date1.setTime(date1temp.getTime());
}
else return false; // otherwise exits

if (isValidDate(charges.date8b.value) && isValidTime(charges.secondtime.value)) { // Validates second date
date2temp = new Date(charges.date8b.value + " " + charges.secondtime.value);
date2.setTime(date2temp.getTime());
}
else return false; // otherwise exits
Oh, by the way, current date format must be "mm/dd/yyy".
Thanks

mwinter
09-17-2006, 07:14 PM
It goes without saying that I'm very much in the learning stages of JS. The biggest problem I've had is finding examples that explain adaquately how to deal with form input, etc.

You should start by reading the comp.lang.javascript FAQ (http://www.jibbering.com/faq/). Entry 4.13 discusses the basics of accessing form controls, and the related FAQ notes (linked at the end of the entry) goes into into more detail.

As for validating user input, you really need to get to grips with regular expressions. If you're not familiar with them, they're a powerful pattern matching tool, though quite intimidating at first. All I can really recommend is that you find a good tutorial and then practice. You can also ask here for help, of course. :)



and the logic and syntax for coding.

There's no simple solution to that. Having programming experience in any C-like language (including Java) will help as the syntax and control structures are quite similar. However, ECMAScript derivatives like JavaScript are also quite unique, and it takes time and effort to learn the language properly.

You might begin with the JavaScript 1.5 Guide (http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide). I started with the earlier (and now out-of-date) 1.3 version. Be aware that this is oriented towards the language as implemented by Mozilla, so there will be some features that aren't found in other browser implementations, but it should help with understanding the basics. Also, note that the object model (the features exposed by the browser) are documented separately, but one thing at a time.

After that, the best source of information, in my opinion, is the comp.lang.javascript newsgroup (your ISP might provide Usenet access, but there are also some free providers around). Usenet isn't always a friendly place[1], but perceived abuse isn't personal: it's usually apathy at answering the same question for the millionth time. At the time when I still misunderstood the language, I found myself on the recieving end of some very blunt corrections, but they proved to be lessons that I never forgot (which was the point). If you really want to understand things, that's the place to learn.



What braces in function did I leave out?

The ones that should surround the function body:



function CalcNow() {
/* ... */
}

Like in other languages, braces that form blocks (such as those that follow statements like if and for) can be omitted if that block contains only one statement:



if (condition) {
someFunction();
}

can also be written as:



if (condition)
someFunction();

However, sometimes they are required. There's no harm in always using them.



Can you give an example of the formal argument? How should it be in the form and function?

A formal argument is simply a named argument in the function declaration. For example,



function f(x, y) {
}

the function f has two formal arguments: x, and y.



You said:

Can you give an example or further explain how you would deal with this? Perhaps some code or reference to a code snippet?

What were you referring to there?



Do you mean that statements like:

var today = new Date()
should end with a semicolon like this?

var today = new Date();

Yes.



function parseDate(string, preferMDY) {
var match, year, month, date, result;

if ((match = /^(\d{4})([.\/-])(\d{1,2})\2(\d{1,2})$/.exec(string))) {
year = +match[1];
month = +match[3];
date = +match[4];
} else if ((match = /^(\d{1,2})([.\/-])(\d{1,2})\2(\d{4})$/.exec(string))) {
year = +match[4];

if (preferMDY) {
month = +match[1];
date = +match[3];
} else {
month = +match[3];
date = +match[1];
}
if (month > 12) {
var temp = month;

month = date;
date = temp;
}
}
with ((result = new Date(year, --month, date)))
if ((month == getMonth()) && (date == getDate())) return result;
return null;
}
function computeDayDifference(from, to) {
from = new Date(+from);
from.setHours(0, 0, 0, 0);
to = new Date(+to);
to.setHours(0, 0, 0, 0);

return Math.round((to - from) / 864e5);
}

Two functions are defined above: parseDate and computeDayDifference.

The first, parseDate, takes two arguments: a string containing a formatted date, and a boolean that helps determine how to handle dates in an ambiguous (##-##-####) format. Once parsed, the date is validated and either a new Date object is returned, or null.

The preferred form for the date is yyyy-mm-dd (though the hyphens can be replaced by dots [.] or slashes [/]) as this is the international date format, and easily recognised. If the format used is dd-mm-yyyy or mm-dd-yyyy, the function will try to make a simple guess as to which one is meant. If it cannot (both the two digit numbers are less than 12), it will assume that the month is first if the second argument is true, or the date is first if the argument is false or omitted. For example,



parseDate('19/09/2007', true)

the second argument would normally have the function treat that sort of string as mm-dd-yyyy, but because the supposed "month" is greater than 12, it will assume otherwise.

The second function, computeDayDifference, takes two arguments, both of which are dates (Date objects) in local time. The return value is the integer number of days difference between the two; a positive number indicates that the second date (to) follows the former (from).



function performCalculation(form) {
var controls = form.elements,
target = parseDate(controls.date.value, true); // Prefer mm-dd-yyyy

controls.days.value = target
? computeDayDifference(new Date(), target) + ' days'
: 'Invalid date format!';
}



<form action="">
<fieldset>
<legend>Days from today</legend>
<label>Enter date (yyyy-mm-dd)</label>:
<input name="date" type="text" value="">
<input type="button" value="Calculate" onclick="performCalculation(this.form);"><br>
<input name="days" type="text" value="" disabled>
</fieldset>
</form>

Hope that helps,
Mike


[1] Please keep in mind that any hostility you might see directed at a poster that goes by the name VK, including any from yours truly, is deserved. VK is the group's resident idiot who has a tendency to post misleading information (though he believes himself to be correct). Ignore anything he writes unless it is corroborated by someone else.

SunKiss
09-17-2006, 08:43 PM
WOW,
Thanks a million, Mike!! That's exactly the kind of teaching and instructions I needed. Little by little I'm getting more and more of this and I really appreciate the time you took to elaborate on all this. I will have to re-read your entire post a couple times or more to ubsorb it all. I will check out your reference to comp.lang.javascript FAQ and the java script guide. The more code I read the more I learn. And your explaination has really helped !!! I'll get there.
Thanks again,
Mark