本文介紹了從日期中減去一定數量的小時、天、月或年的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
我正在嘗試創建一個簡單的函數,它返回一個從現在開始減去一定天數的日期,所以類似這樣的事情,但我不太了解日期類:
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));
這篇關于從日期中減去一定數量的小時、天、月或年的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!