Ron*_*ieT 4 php datetime date strtotime datetime-format
我有一个日期字符串格式化为March 8 - 10未提供年份的日期,但根据日历年的当前日期,这将是明年3月的日期.
提供准确年份的最佳方法是什么时间与上述类似的日期是在12月31日之后?
考虑下面$sdate > $now这样的事情然而这将比任何日期增加+1年,而不是将12月31日视为当年年底.
$dates = trim('March 8 - 10');
$now = date("Y-m-d",strtotime("now"));
if (strpos($dates,'-') !== false) {
$sdate = trim(substr($dates, 0, strpos($dates, '-')));
if ($sdate > $now) {
$sdate = strtotime("+1 year", strtotime($sdate));
$sdate = date("Y-m-d", $sdate);
}
$month = substr($sdate, 0, strpos($sdate, ' '));
$edate = $month.substr($dates, -2, strpos($dates, '-'));
$edate = date("Y-m-d",strtotime($edate));
}
Run Code Online (Sandbox Code Playgroud)
我想你正在寻找这样的东西:
$in = trim('March 8 - 10');
$now = new DateTimeImmutable(); // Defaults to now
$start = DateTimeImmutable::createFromFormat('F j+', $in); // Parse month and day, ignore the rest
if ($now > $start) {
$start = $start->modify("next year");
}
$end = $start->setDate(
$start->format('Y'), // $start year
$start->format('n'), // $start month
substr($in, strrpos($in, ' ') + 1) // trailing bit of $in for day
);
echo $start->format("Y-m-d"), "\n";
echo $end->format("Y-m-d");
Run Code Online (Sandbox Code Playgroud)
2016-03-08
2016-03-10
Run Code Online (Sandbox Code Playgroud)
给定一个像'November 8 - 10'它输出的字符串:
2015-11-08
2015-11-10
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
216 次 |
| 最近记录: |