Comparing DateTime........please help

P

prashanth

Hi all,
I am unable to write a javascript which will allow me to compare
datetime entered by the user with the current datetime.( i.e the
usertime should be less than or greater than currenttime)

Thanx a lot in advance
 
B

Brian Genisio

prashanth said:
Hi all,
I am unable to write a javascript which will allow me to compare
datetime entered by the user with the current datetime.( i.e the
usertime should be less than or greater than currenttime)

Thanx a lot in advance

Here is a start... in this example, you can type two forms of the date
in the box:
January 20, 2004
January 20, 2004 10:30:22

Of course, they need to be entered in exactly, so you will likely set up
your form for better user input, and create the string yourself.

The date constructor has the following formats:
new Date("Month dd, yyyy hh:mm:ss")
new Date("Month dd, yyyy")
new Date(yy,mm,dd,hh,mm,ss) // where month is an integer
new Date(yy,mm,dd)
new Date(milliseconds) // milliseconds since January 1, 1970

Here is the code I came up with... play with it how you need:

<HTML>
<HEAD>
<SCRIPT>
function compareDate()
{
var currentDate = new Date();
var userDate =
new Date(document.getElementById("user_date").value);

if(userDate <= currentDate)
alert("SUCCESS");
else
alert("FAILURE");

return false;
}
</SCRIPT>
</HEAD>

<BODY>
<FORM>
<INPUT TYPE=text ID=user_date>
<INPUT TYPE=submit onClick="return compareDate();">
</FORM>
</BODY>
</HTML>
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
news:comp.lang.javascript said:
prashanth wrote:

Here is a start... in this example, you can type two forms of the date
in the box:
January 20, 2004
January 20, 2004 10:30:22

Of course, they need to be entered in exactly, so you will likely set up
your form for better user input, and create the string yourself.

The date constructor has the following formats:
new Date("Month dd, yyyy hh:mm:ss")
new Date("Month dd, yyyy")
new Date(yy,mm,dd,hh,mm,ss) // where month is an integer one smaller than normal
new Date(yy,mm,dd)
new Date(milliseconds) // milliseconds since January 1, 1970
GMT

The above is not a complete list.

OP: you don't give an area-of-use. The code already given will accept,
I believe, both 17/03/04 and 03/17/04 as St Patrick's Day; but not
17/03/04, which is what is most generally used for that date.
Therefore, the form should not be encouraged. 2004/03/17 is safe.

To validate as being a proper date, see below.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top