Shakti Singh
Shakti Singh

Reputation: 86336

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.

Upvotes: 87

Views: 211426

Answers (10)

Shweta
Shweta

Reputation: 799

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

Upvotes: 7

Rashed Rahat
Rashed Rahat

Reputation: 2479

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

Upvotes: 2

Hiba
Hiba

Reputation: 101

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

Upvotes: 3

carnini
carnini

Reputation: 65

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.

Upvotes: 5

bidon
bidon

Reputation: 3

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

Upvotes: 0

Vineesh K S
Vineesh K S

Reputation: 1964

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

You can use explode also

Upvotes: 0

fvox
fvox

Reputation: 163

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

Upvotes: 2

Maerlyn
Maerlyn

Reputation: 34107

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

Upvotes: 117

Sarfraz
Sarfraz

Reputation: 382608

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

Upvotes: 79

dshipper
dshipper

Reputation: 3529

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

Upvotes: 0

Related Questions