Get year from specified php date

I have a date in this format 2068-06-15 . I want to get the year from the date using php functions. Can anyone suggest how this can be done.

+46
date php
Dec 25 '10 at 7:44
source share
8 answers
 $date = DateTime::createFromFormat("Ymd", "2068-06-15"); echo $date->format("Y"); 

The DateTime class does not use the unix timestamp inside, so it processes dates before 1970 or after 2038.

+60
Dec 25 '10 at 7:57
source share

You can use strtotime and date acts as follows:

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

Please note that PHP can handle the year until 2038

You can check it out here.




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

 $parts = explode('-', '2068-06-15'); echo $parts[0]; 
+38
Dec 25 2018-10-12T00:
source share

 <?php list ($ year) = explode ( "-", "2068-06-15" ); echo $year; ?> > 
+2
Dec 25 '10 at 8:17
source share

I would use this:

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

It seems that the date comes from the source, where it is always the same, much faster using explode.

+1
Jul 10 '13 at 23:09
source share
  public function getYear($pdate) { $date = DateTime::createFromFormat("Ymd", $pdate); return $date->format("Y"); } public function getMonth($pdate) { $date = DateTime::createFromFormat("Ymd", $pdate); return $date->format("m"); } public function getDay($pdate) { $date = DateTime::createFromFormat("Ymd", $pdate); return $date->format("d"); } 
+1
Jan 21 '14 at 13:13
source share

Assuming you have a date as a string (sorry, it was not clear from your question, if so), you can break the string into-characters as follows:

 $date = "2068-06-15"; $split_date = split("-", $date); $year = $split_date[0]; 
0
Dec 25 '10 at 7:49
source share
 $Y_date = split("-","2068-06-15"); $year = $Y_date[0]; 

You can also use explode

0
Nov 12
source share

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

 $parts = explode("-","2068-06-15"); for ($i = 0; $i < count($parts); $i++) { if(strlen($parts[$i]) == 4) { $year = $parts[$i]; break; } } 
0
Jul 10 '13 at 23:32
source share