Get the year from specified date php

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.

181446 次浏览

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

You can test it out here


If your date is always in that format, you can also get the year like this:

$parts = explode('-', '2068-06-15');
echo $parts[0];

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];
$date = DateTime::createFromFormat("Y-m-d", "2068-06-15");
echo $date->format("Y");

The DateTime class does not use an unix timestamp internally, so it han handle dates before 1970 or after 2038.

<?php
list($year) = explode("-", "2068-06-15");
echo $year;
?>

$Y_date = split("-","2068-06-15");
$year = $Y_date[0];

You can use explode also

I would use this:

$parts = explode('-', '2068-06-15');
echo $parts[0];

It appears the date is coming from a source where it is always the same, much quicker this way using explode.

You wrote that format can change from YYYY-mm-dd to dd-mm-YYYY you can try to find year there

$parts = explode("-","2068-06-15");
for ($i = 0; $i < count($parts); $i++)
{
if(strlen($parts[$i]) == 4)
{
$year = $parts[$i];
break;
}
}
  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");
}

You can achieve your goal by using php date() & explode() functions:

$date = date("2068-06-15");

$date_arr = explode("-", $date);

$yr = $date_arr[0];

echo $yr;

That is it. Happy coding :)

You can try strtotime() and date() functions for output in minimum code and using standard way.

echo date('Y', strtotime('2068-06-15'));

output: 2068

echo date('y', strtotime('2068-06-15'));

output: 68