Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php how to go from day of the year to date and vice versa

Tags:

date

php

How do you go in php from a nth day in the year to the date like:

getdatefromday(275, 2012) 

and it outputs a date (better if an object).

And I'd like to do the opposite too, like getdayoftheyear("21 oct 2012")

like image 628
gotch4 Avatar asked Mar 16 '12 10:03

gotch4


2 Answers

This is pretty easy all around. You should read up on the DateTime object's createFromFormat static method here, the date function here and the strtotime function here.

// This should get you a DateTime object from the date and year.
function getDateFromDay($year, $dayOfYear) {
  $date = DateTime::createFromFormat('z Y', strval($year) . ' ' . strval($dayOfYear));
  return $date;
}

// This should get you the day of the year and the year in a string.
date('z Y', strtotime('21 oct 2012'));
like image 159
Steven Oxley Avatar answered Sep 20 '22 17:09

Steven Oxley


Try(days starts from 0 not 1):

$date = DateTime::createFromFormat( 'Y z' , '2012 275');
var_dump($date);

and that:

echo date('z', strtotime('21 oct 2012'));
like image 45
Vytautas Avatar answered Sep 18 '22 17:09

Vytautas