vit*_*tto 12 php time datetime timestamp date
我正在尝试创建一个简单的函数,它返回一个日期,从现在起减去一定数量的日期,所以这样的事情,但我不知道日期类很好:
<?
function get_offset_hours ($hours) {
return date ("Y-m-d H:i:s", strtotime (date ("Y-m-d H:i:s") /*and now?*/));
}
function get_offset_days ($days) {
return date ("Y-m-d H:i:s", strtotime (date ("Y-m-d H:i:s") /*and now?*/));
}
function get_offset_months ($months) {
return date ("Y-m-d H:i:s", strtotime (date ("Y-m-d H:i:s") /*and now?*/));
}
function get_offset_years ($years) {
return date ("Y-m-d H:i:s", strtotime (date ("Y-m-d H:i:s") + $years));
}
print get_offset_years (-30);
?>
Run Code Online (Sandbox Code Playgroud)
是否可以做类似的事情?这种功能可以使用多年,但如何与其他时间类型相同?
Ale*_*exV 22
用了几个小时:
function get_offset_hours($hours)
{
return date('Y-m-d H:i:s', time() + 3600 * $hours);
}
Run Code Online (Sandbox Code Playgroud)
这样的东西可以在数小时和数天内使用(使用86400天),但是几个月和一年它有点棘手......
你也可以这样做:
$date = strtotime(date('Y-m-d H:i:s') . ' +1 day');
$date = strtotime(date('Y-m-d H:i:s') . ' +1 week');
$date = strtotime(date('Y-m-d H:i:s') . ' +2 weeks');
$date = strtotime(date('Y-m-d H:i:s') . ' +1 month');
$date = strtotime(date('Y-m-d H:i:s') . ' +30 days');
$date = strtotime(date('Y-m-d H:i:s') . ' +1 year');
echo(date('Y-m-d H:i:s', $date));
Run Code Online (Sandbox Code Playgroud)
Phi*_*off 11
尝试使用 datetime::sub
来自docs(链接)的示例:
<?php
$date = new DateTime("18-July-2008 16:30:30");
echo $date->format("d-m-Y H:i:s").'<br />';
date_sub($date, new DateInterval("P5D"));
echo '<br />'.$date->format("d-m-Y").' : 5 Days';
date_sub($date, new DateInterval("P5Y5M5D"));
echo '<br />'.$date->format("d-m-Y").' : 5 Days, 5 Months, 5 Years';
date_sub($date, new DateInterval("P5YT5H"));
echo '<br />'.$date->format("d-m-Y H:i:s").' : 5 Years, 5 Hours';
?>
Run Code Online (Sandbox Code Playgroud)