Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get only the year part of a date string?

Tags:

date

php

I have an input date by user like this: 1979-06-13

Now, i want to compare the year:

foreach ($list as $key) {
    $year = 1979;
    if ($key > $year) { //only the year
        echo (error);
        }
}

How can I get only the year?

Thanks

like image 832
daniel__ Avatar asked Jun 22 '11 00:06

daniel__


3 Answers

Probably more expensive, but possibly more flexible, use strtotime() to convert to a timestamp and date() to extract the part of the date you want.

$year = date('Y', strtotime($in_date));
like image 165
bmb Avatar answered Oct 15 '22 23:10

bmb


With strtok:

$year = strtok($date, '-');

If you want the year as integer, you can also use intval:

$year = intval($date);
like image 38
Felix Kling Avatar answered Oct 16 '22 00:10

Felix Kling


Heres an easy and exact way.

//suppose
$dateProvided="1979-06-13";
//get first 4 characters only
$yearOnly=substr($dateProvided,0,4);
echo $yearOnly;
//1979

and one more thing to know, in some cases like, for example when the date is like 2010-00-00 the date function don't work as expected, it would return 2009 instead of 2010. heres an example

//suppose
$dateProvided="2010-00-00";
$yearOnly = date('Y', strtotime($dateProvided));
//we expect year to be 2010 but the value of year would be 2009
echo $yearOnly;
//2009
like image 22
aimme Avatar answered Oct 15 '22 22:10

aimme