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")
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'));
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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With