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
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));
With strtok
:
$year = strtok($date, '-');
If you want the year as integer, you can also use intval
:
$year = intval($date);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With