Wednesday, February 9, 2011

How can I just get the "Year" portion from the output of timespan() in CodeIgniter?

I have a Date of Birth field and trying to use the timespan function to get the age, but returns "28 Years, 2 Months, 2 Weeks, 3 Days, 15 Hours, 16 Minutes".

Any idea how I can just get the "28 Years" part?

Thanks!

  • There are many ways to do this, with the string in $date, like so:

    $date = '28 Years, 2 Months, 2 Weeks, 3 Days, 15 Hours, 16 Minutes';
    
    This will give you "28 Years"
    $yearsPart = substr($date, 0, strpos($date, 'Years') + 5);
    
    So will this:
    $parts = split(', ', $date);
    $yearsPart = $parts[0];
    
    From Kevin Chan
  • I suggest you use PHP's strftime() function. Instead of using the CI's timespan().

    echo strftime('%Y', 1226239392);

0 comments:

Post a Comment