'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.



Solution 1:[1]

$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.

Solution 2:[2]

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];

Solution 3:[3]

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.

Solution 4:[4]

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

Solution 5:[5]

  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");
}

Solution 6:[6]

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

Solution 7:[7]

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 :)

Solution 8:[8]

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];

Solution 9:[9]

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

You can use explode also

Solution 10:[10]

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;
      }
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maerlyn
Solution 2
Solution 3 CuberChase
Solution 4
Solution 5 Hiba
Solution 6 fvox
Solution 7 Rashed Rahat
Solution 8 dshipper
Solution 9 Vineesh Kalarickal
Solution 10 bidon