Difference between two dates in php?

Discussion in 'PHP' started by Alice24, Aug 9, 2009.

  1. #1
    i want to calculate difference of 2 dates and i have a little error.
    if the days are in the same month everything works perfect.
    but if 1 day is from a month ago the result is not good.
    for example:
    $now= date('d.m.Y');
    $date= "28.07.2009" ;
    $diference= ($now - $date);

    echo "$diference";

    it print's me something like -18.99

    what is wrong?
     
    Alice24, Aug 9, 2009 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    You should convert the date to a timestamp to do any sort of mathimatical operation on it.

    Something like:

    $now = time();

    $then = strtotime("28.07.2009");

    $difference = $now - $then; //In Seconds

    You can convert seconds to whatever denomination you need. *60 for Minutes, *3600 For Hours, etc...
     
    jestep, Aug 9, 2009 IP
  3. kblessinggr

    kblessinggr Peon

    Messages:
    539
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    0
    #3
    You can't subtract strings. You'll need to convert the string-based format to an actual unix time (strtotime() I belive would do it). Then you can subtract the earlier time from the later time to get an actual difference in value.

    Otherwise what you're doing is "9.08.2009' - "28.07.2009" which mathematically makes no sense.
     
    kblessinggr, Aug 9, 2009 IP
  4. Alice24

    Alice24 Greenhorn

    Messages:
    59
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    16
    #4
    It works.

    $date1 = $row['date'] ;
    $date2 = date('d.m.Y');

    $d1 = explode(".",$date1);
    $d2 = explode(".",$date2);

    $days = floor(abs(mktime(0,0,0,$d1[1],$d1[0],$d1[2]) - mktime(0,0,0,$d2[1],$d2[0],$d2[2])) / (60*60*24));

    echo $days;

    Thank you @jestep
     
    Alice24, Aug 9, 2009 IP