On Sep 21, 12:18 am, Castro <
dvas...@gmail.com> wrote:
> Hi there!
> I've a simple question about date comparison. In DB stored data and
> I'd like to limit access to data older then 21 apr 2010. User clicking
> to 'Next' or 'Previous' buttons for displaying neccessary data on a
> page
>
> var a = $("#counter").val();
> var t1 = new Date();
That will create a date with the current time.
> t1.setFullYear(2010, 4, 21);
That changes the year, month and day to specific values but the time
is whatever it was when the date object was created.
> var d = new Date();
That creates another date object at a different time. Since computers
are pretty fast and time is only measured to 0.001 seconds, most of
the time it will have the same time as t1, but sometimes it will be
different by 1ms (or maybe more).
> //also I use it later for params genaration
> var current_date = d.getDate();
> var current_month = d.getMonth()+1;
> var current_year = d.getFullYear();
>
> var t2 = new Date();
> t2.setFullYear(current_year,current_month, current_date);
That creates another date object, it is extremely unlikely that the
year, month or day will be different to d, but it might be if the date
objects are created at almost exactly midnight. If you want to create
a second date object with the same date and time as another, use:
var t2 = new Date(d.getTime());
> //if user came to 21 apr 2010 this condition finishes executed
>
> if(!t1.equals(t2.add(-counter).days())){
> //AJAX request
If you are comparing date objects and time is not relevant, set the
time to zero, or create the date objects with zero time in the first
place, so:
// Create date object 2010/04/21 00:00:00.000
var t1 = new Date(2010, 4, 21);
// Create date object with today's date and time 00:00:00.000
var d = new Date();
var t2 = new Date(d.getFullYear(), d.getMonth()+1, d.getDate());
or:
var t2 = new Date();
t2.setHours(0, 0, 0);
Now t1 and t2 have a time of 00:00:00 so comparisons effectively only
involve the date. To add or subtract days from a date object:
// Add one day
t2.setDate(t2.getDate() + 1);
// Subtract one day
t2.setDate(t2.getDate() - 1);
Because the time is 00:00:00.000 you can compare them as:
if (t1.getTime() == t2.getTime()) {
// Same date
}
>
> }
>
> So I don't know is it correct code but sometimes it working and I see
> alert. But often nothing happens. Why?
Probably because sometimes when the date is the same, the time is
different by 1ms, so "equals" isn't true.
--
Rob