So I have the number of days and the year in the following format:

322 days
2009 year

I need to convert this to 2009-11-18

Is there a function in php to achieve this?

有帮助吗?

解决方案

Sure, use mktime and date:

$days = 322;
$year = 2009;
echo date('Y-m-d', mktime( 0, 0, 0, 1, $days, $year));

Output: 2009-11-18

其他提示

$newformat = new DateTime::createFromFormat('Y z', "2009 322")->format('Y-M-d');

Relevant docs here: http://php.net/manual/en/datetime.createfromformat.php

We do have strtotime() in php, which can easily pull timestamp from year:

echo $time = strtotime( '1.1.2009');
// 1230764400

And chain it with adding days:

echo $newTime = strtotime( '+322 days', $time);
// 1258585200
echo date( 'r', $newTime);
// Thu, 19 Nov 2009 00:00:00 +0100
echo date( 'Y-m-d', $newTime);
// 2009-11-19
// output will be 19 instead of 18 (due to how strtotime handles + days), you
// should use +321 days instead than

btw: I like Marc B's answer better .)

The hard way ( and as a bonus, I parse the input example you gave :p ):

list($day, $foo, $year, $bar) = sscanf("322 days 2009 year", "%d %s %d %s");
$timestamp = mktime (0,0,0, 1, $day, $year);
echo date('Y-m-d', $timestamp);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top