从日期减去一定数量的小时、天、月或年 [英] Subtracting a certain number of hours, days, months or years from date

查看:15
本文介绍了从日期减去一定数量的小时、天、月或年的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的函数,它返回一个从现在开始减去一定天数的日期,所以像这样,但我不太了解日期类:

I'm trying to create a simple function which returns me a date with a certain number of subtracted days from now, so something like this but I dont know the date classes well:

<?
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);
?>

是否可以做类似的事情?这种功能可以使用多年,但其他时间类型如何做到这一点?

Is it possible to do something similar to this? this kind of function works for years, but how to do the same with other time types?

推荐答案

几个小时:

function get_offset_hours($hours)
{
    return date('Y-m-d H:i:s', time() + 3600 * $hours);
}

类似的东西在几个小时和几天内都可以正常工作(几天使用 86400),但是对于几个月和一年来说,它有点棘手......

Something like that will work well for hours and days (use 86400 for days), but for months and year it's a bit trickier...

你也可以这样做:

$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));

这篇关于从日期减去一定数量的小时、天、月或年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆