1. Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

Get an age from dates in PHP/SQL

Discussion in 'Programming & Webmastering' started by Akumos, May 23, 2013.

  1. Akumos

    Akumos

    Joined:
    Nov 30, 2008
    Messages:
    552 (0.24/day)
    Thanks Received:
    28
    Location:
    Birmingham, England...
    Hello

    I'm looking for an easy way to extract how many days a table entry has been there, from an SQL db into a PHP website.

    For example, when the item is inserted, it gets DATE(2013-05-20). I want my session variable to extract that date, then use the current date to determine how many days it's been there. I was thinking something like:

    $_SESSION['age'] = new DateTime(date('Y-m-d')) - ("yyyy/mm/dd") - $dbRecord["age"];

    but in the example above, this returns -2012 Days

    Thanks for you help :)
     
  2. W1zzard

    W1zzard Administrator Staff Member

    Joined:
    May 14, 2004
    Messages:
    15,309 (3.83/day)
    Thanks Received:
    12,473
    DATEDIFF() in MySQL

    Also look up NOW(), you don't seem to know about it

    you could also do it in PHP, I recommend UNIX_TIMESTAMP() in MySQL, so you get the time in a format that PHP likes better than a date string.

    PHP function strtotime() is REALLY nice to work with dates, too
     
    Akumos says thanks.
  3. Akumos

    Akumos

    Joined:
    Nov 30, 2008
    Messages:
    552 (0.24/day)
    Thanks Received:
    28
    Location:
    Birmingham, England...
    Thanks for the quick reply :) I'll get reading and report back if I need further help!
     
  4. Akumos

    Akumos

    Joined:
    Nov 30, 2008
    Messages:
    552 (0.24/day)
    Thanks Received:
    28
    Location:
    Birmingham, England...
    Worked perfectly using a combination of the two, thanks for the very quick reply w1zzard, appreciate your help

    $sql = "SELECT DATEDIFF(now(),age) AS item_age FROM item WHERE item_id = ".$_SESSION['item_id']
     

Currently Active Users Viewing This Thread: 1 (0 members and 1 guest)

Share This Page