Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Year From Date string

Tags:

html

php

I want to check whether the current year is greater than a date string(D-M-Y) here is my code

$OldDate = "09-30-2011";
$OldYear = strtok($OldDate, '-');
$NewYear = date("Y");

if ($OldYear < $NewYear) {
    echo "Year is less than current year"   
} else {
    echo "Year is greater than current year";
}
like image 207
Rakesh Avatar asked Dec 26 '22 17:12

Rakesh


1 Answers

You can use strtotime():

$OldDate = "2011-09-30";

$oldDateUnix = strtotime($OldDate);
if(date("Y", $oldDateUnix) < date("Y")) {
    echo "Year is less than current year";
} else {
    echo "Year is greater than current year";
}

UPDATE

Because you're using an unconventional datestamp, you have to use different methods, eg:

$OldDate = "09-30-2011";
list($month, $day, $year) = explode("-", $OldDate);
$oldDateUnix = strtotime($year . "-" . $month . "-" . $day);
if(date("Y", $oldDateUnix) < date("Y")) {
    echo "Year is less than current year";
} else {
    echo "Year is greater than current year";
}

NOTE: If you want to always be sure that your date gets correctly understood by strtotime, use YYYY-MM-DD

like image 110
h2ooooooo Avatar answered Dec 29 '22 07:12

h2ooooooo