PHP如何将3212年(YDDD)的日期反向工程到2013-08-01(YYYY-mm-dd)


PHP How to reverse engineer the day of the year 3212 (YDDD) into 2013-08-01 (YYYY-mm-dd)

我有一个YDDD格式的日期,例如3212
我想将此日期转换为默认日期字符串,即PHP中的2013-08-01
由于第一个值Y是年份的唯一字符,因此我决定从当前年份中提取前三个字符,即2013年的201
以下是我为年度编写的代码

<?php
$date = "3212"
$y = substr($date,0,1); // will take out 3 out of year 3212
$ddd = substr($date,1,3); // will take out 212 out of year 3212
$year = substr(date("Y"),0,3) . $y; //well create year "2013"
?>

现在我如何使用$year212使用PHP 将其转换为2013-08-01

编辑
仅供参考:我的PHP版本是5.3.6

$date = "3212";
echo DateTime::createFromFormat("Yz", "201$date")->format("Y-m-d");
// 2013-08-01
  • DateTime::createFromFormat()
  • 看到它在线运行
$yddd = 3212;
preg_match('/^('d)('d{3})$/', $yddd, $m);
echo date('Y-m-d', strtotime("201{$m[1]}-01-01 00:00:00 +{$m[2]} days"));

如果您在PHP 5.3或更高版本上运行代码,您可以使用date_create_from_format将$year和$ddd转换为可用日期。例如:

$date = date_create_from_format("Y-z", "$year-$ddd");
echo date_format($date, "Y-m-d");
// Formatted Date (YDDD)
$dateGiven = "3212";
// Generate the year based on the first digit
$year = substr(date("Y"),0,3).substr($dateGiven,0,1);
// Split out the day of the year
$dayOfTheYear = substr($dateGiven,1,3);
// Create a date object from the formatted date
$date = DateTime::createFromFormat('z Y',  "{$dayOfTheYear} {$year}");
// Output the date in the desired format
echo $date->format('Y-m-d');

在线查看:https://eval.in/private/69daafa849ee36