compare dates

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
gurjit
Forum Contributor
Posts: 314
Joined: Thu May 15, 2003 11:53 am
Location: UK

compare dates

Post by gurjit »

hi all,

i have two dates for example

08/11/2004 and 10/11/2004

i want compare the number of days between these two dates. in the above there are 2 days before its is the 10/11/2004.

i tried this and it does'nt work. gives the wrong number of days

Code: Select all

<?php
$var_from_todayd = date("d");
$var_from_todaym = date("m");
$var_from_todayy = date("Y");

$var_to_todayd = date("d",strtotime($get_school_longestP['t_edate']));
$var_to_todaym = date("M",strtotime($get_school_longestP['t_edate']));
$var_to_todayy = date("Y",strtotime($get_school_longestP['t_edate']));
$diffP=abs(mktime(0,0,0,$var_from_todaym,$var_from_todayd,$var_from_todayy)-mktime(0,0,0,$var_to_todaym,$var_to_todayd,$var_to_todayy))/(86400);

?>
malcolmboston
DevNet Resident
Posts: 1826
Joined: Tue Nov 18, 2003 1:09 pm
Location: Middlesbrough, UK

Post by malcolmboston »

User avatar
gurjit
Forum Contributor
Posts: 314
Joined: Thu May 15, 2003 11:53 am
Location: UK

Post by gurjit »

how do i do that in the above?
User avatar
liljester
Forum Contributor
Posts: 400
Joined: Tue May 20, 2003 4:49 pm

Post by liljester »

looks like you're already using timestamps, so you're half way there...

if you want to know how many days are between to dates, id do it like this:

Code: Select all

$first_date = mktime(0,0,0,8,11,2004);
$second_date = mktime(0,0,0,10,11,2004);

$difference = $second_date - $first_date;

$days = $difference / 86400;

// $days calculates to 61  which is correct i think =)  //
youre formula may be wrong =)
User avatar
liljester
Forum Contributor
Posts: 400
Joined: Tue May 20, 2003 4:49 pm

Post by liljester »

wait hold the phone... you said your dates are 2 days apart??? those dates are 2 MONTHS apart. (MM, DD, YYYY)
User avatar
gurjit
Forum Contributor
Posts: 314
Joined: Thu May 15, 2003 11:53 am
Location: UK

Post by gurjit »

if i had a date as today

08/march/2004

and a second date as

10/march/2004

i should get 2 days difference. thats what i'm lloking for.
User avatar
liljester
Forum Contributor
Posts: 400
Joined: Tue May 20, 2003 4:49 pm

Post by liljester »

you're using the wrong date format... use MM, DD, YYYY... not DD, MM, YYYY.

mktime(hours, minutes, seconds, month, day, year);
User avatar
gurjit
Forum Contributor
Posts: 314
Joined: Thu May 15, 2003 11:53 am
Location: UK

Post by gurjit »

works wonders my friend.

thanks for your help. my top code worked too. just that i was doing this line wrong and calling "M" instead of "m"

$var_to_todaym = date("m",strtotime($get_school_longestP['t_edate']));



thanks for your time.
Post Reply