3

I have on function which passing some parameter the like

everyWeekOn("Mon",11,19,00)

I want to compute the difference between the current day (e.g. 'Fri') and passed parameter day i.e. Mon.

The output should be:

The difference between Mon and Fri is 3

I tried it like this

 $_dt = new DateTime();
 error_log('$_dt date'. $_dt->format('d'));
 error_log('$_dt year'. $_dt->format('Y'));
 error_log('$_dt month'. $_dt->format('m'));

But know I don't know what to do next to get the difference between the two days.

Note that this question is different from How to calculate the difference between two dates using PHP? because I only have a day and not a complete date.

Community
  • 1
  • 1

3 Answers3

3

Just implement DateTime class in conjunction with ->diff method:

function everyWeekOn($day) {
    $today = new DateTime;
    $next = DateTime::createFromFormat('D', $day);
    $diff = $next->diff($today);
    return "The difference between {$next->format('l')} and {$today->format('l')} is {$diff->days}";
}

echo everyWeekOn('Mon');
Kevin
  • 41,694
  • 12
  • 53
  • 70
  • 1
    thax @ghost you save my ass ;) –  Apr 17 '15 at 06:37
  • Awesome buddy thax for the help –  Apr 17 '15 at 06:37
  • hey ghost can you explain just what is $next->format('l') pls –  Apr 17 '15 at 06:43
  • @Sanji its the same thing with `date('l')`, (thats small L) http://php.net/manual/en/function.date.php its using the same format. and the [`->format()`](http://php.net/manual/en/datetime.format.php) – Kevin Apr 17 '15 at 06:49
1
$date = new DateTime('2015-01-01 12:00:00');
$difference = $date->diff(new DateTime());
echo $difference->days.' days <br>';
Maxim Lazarev
  • 1,254
  • 12
  • 21
0

You can find no. of days in two days by using this code

<?php
    $today = time(); 
    $chkdate = strtotime("16-04-2015");
    $date = $today - $chkdate;
    echo floor($date/(60*60*24));
?>

Please use this may this help you

MackieeE
  • 11,751
  • 4
  • 39
  • 56
Sourabh
  • 500
  • 2
  • 14
  • 1
    WATCH OUT: not all days are 86400 (60*60*24) seconds long! This may have unexpected results if the server is not using UTC as timezone! Use `DateTime` and its methods instead. – ItalyPaleAle Apr 17 '15 at 14:15