I have a date in this format 2068-06-15. I want to get the year from the date, using php functions. Could someone please suggest how this could be done.
10 Answers
You can use the strtotime and date functions like this:
echo date('Y', strtotime('2068-06-15'));
Note however that PHP can handle year upto 2038
If your date is always in that format, you can also get the year like this:
$parts = explode('-', '2068-06-15');
echo $parts[0];
6 Comments
Shakti Singh
I already tried this but it is giving me 1970 that it is why php can't read the year above the 2038. right?
Sarfraz
@Shakti: Because as i have said in my answer, PHP can handle year up to 2038 and you have specified 2068. You can test it here: codepad.org/iwqtML6s
Shakti Singh
ya, I agree with you but I have maximum input 2069. so I think I have to use substr or similar function which can split it but the problem is input date fromat can be changed now it is yyyy-mm-dd may be later changed to mm-dd-yyyy
Sarfraz
@Shakti: As i have shown in my answre later, you can get the date with
explode function too: $parts = explode('-', '2068-06-15'); echo $parts[0];. You can test it here: codepad.org/HbS63y2nMaerlyn
I do not understand why you're using unix timestamps when the OP has given an example outside of it's range.
|
public function getYear($pdate) {
$date = DateTime::createFromFormat("Y-m-d", $pdate);
return $date->format("Y");
}
public function getMonth($pdate) {
$date = DateTime::createFromFormat("Y-m-d", $pdate);
return $date->format("m");
}
public function getDay($pdate) {
$date = DateTime::createFromFormat("Y-m-d", $pdate);
return $date->format("d");
}
Comments
Assuming you have the date as a string (sorry it was unclear from your question if that is the case) could split the string on the - characters like so:
$date = "2068-06-15";
$split_date = split("-", $date);
$year = $split_date[0];
1 Comment
Sarfraz
Note that
split is deprecated.