PDA

View Full Version : Date comparison



MSK7
01-02-2010, 02:27 PM
Hello all,

I am entering date from a calender in a textbox named "date" in the formate of (yyyy-mm-dd) like (2010-01-02).

I want to compare the entered date with todays current date ,
so that past date can not be submitted in the textbox.

i am using the code below to get todays current date to compare with text box value :-


var currentTime = new Date();
var Cmonth = currentTime.getMonth() + 1 ;
var Cday = currentTime.getDate();
var Cyear = currentTime.getFullYear();
var Today = (Cyear + "-" + Cmonth + "-" + Cday);
alert(Today);


But it gives todays date in the form of (2009-1-2)
rather than (2009-01-02).

please suggest me how this date can be achieved like (2009-01-02).

Please also suggest how the entered date can be compared with the achieved Todays current date ,
so that past date cannot be submitted.


Thanks & Regards.

jscheuer1
01-02-2010, 02:50 PM
I think you are going about this the wrong way. You don't want to get each part of either the current date or the entered date. You just want to know if the entered date is in the past or not:


<script type="text/javascript">
var dateString = '2010-01-02',
dateEntered = new Date(dateString.replace(/-/g, ',')),
currentDate = new Date();
alert(dateEntered < currentDate);
</script>

This will alert true for an entered date in the past, and for one that is the same date as the current date (except at precisely midnight), false for an entred date in the future or one entered at precisely midnight on the current date. I think you can adapt it to your purposes. If you want more help or have questions, let me know.

djr33
01-02-2010, 11:08 PM
Always when you are using dates, convert them ALL to an easily compared (mathematically) format.
Using a timestamp like John's method above is a good idea.

Another way, if you are bothered by something that is not human-readable, I suggest:
YYYYMMDD without any punctuation.
Then you can compare them as simply greater than (after) or less than (before):
19990130<20001209
(January 30, 1999 is before December 9, 2000)

You must change the format from what is expected by how humans usually write dates, so the computer can read it-- but you don't always have to sacrifice human-readability for computer-readability. Depending on the situation, a method like that can work for both.

The method you are using is in some ways workable, because if you "alphabetize" YYYY-MM-DD, it should go in the right order, but it's not as easy to compare as YYYYMMDD.

In general, even though they are annoying, timestamps are the best way to go because they are the standard and are easy to store, compare and do lots of math on (like subtract 180 seconds, or 3 days, etc.).

For this specific question, just use what John posted above. I hope this helps for future questions/plans, though.