Date calculation in months

Discussion in 'PHP' started by alimoses, Sep 27, 2010.

  1. #1
    I have a table 'members' and a column 'date_created'.
    I want to at any point in time be able to get the number of months between the date_created and the current date.
    Some should help me out
     
    alimoses, Sep 27, 2010 IP
  2. tiamak

    tiamak Active Member

    Messages:
    81
    Likes Received:
    2
    Best Answers:
    3
    Trophy Points:
    58
    #2
    date_created = A
    current_date = B
    (monthB-monthA)+(yearB-yearA)*12
    or something like that ;)
     
    tiamak, Sep 27, 2010 IP
  3. gtk29

    gtk29 Member

    Messages:
    519
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    28
    #3
    echo (int)((strtotime("now") - strtotime($date_created)) / (3600 * 24 * 30));

    here $date_created would hold your date data.
     
    gtk29, Sep 27, 2010 IP
  4. jaholden

    jaholden Peon

    Messages:
    18
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    The above reply will be inaccurate over longer periods because there are not 30 days in every month!

    This should work better:

    
    <?php
    
    $date_created = new DateTime('2009-08-28');
    $interval = $date_created->diff(new DateTime);
    printf("Months: %d\n", 12 * $interval->format('%r%y') + $interval->format('%r%m'));
    
    // Outputs:
    // Months: 13
    
    PHP:
     
    jaholden, Sep 28, 2010 IP
  5. tiamak

    tiamak Active Member

    Messages:
    81
    Likes Received:
    2
    Best Answers:
    3
    Trophy Points:
    58
    #5
    it works only with php 5.3 or higher
     
    tiamak, Sep 28, 2010 IP
  6. lukeg32

    lukeg32 Peon

    Messages:
    645
    Likes Received:
    19
    Best Answers:
    1
    Trophy Points:
    0
    #6
    How are you defining months, and what should happen with "part" months?

    There is no need to do this in PHP when MySQL (or any SQL for that matter) provides you with plenty of date/time functions to do this as part of your SELECT from the database.
     
    lukeg32, Sep 28, 2010 IP