如何在PHP中对日期执行操作

3

我在计算日期时遇到了问题。简单的例子:

我有一个起始日期为2013-09-01,每个月都有30天。我的工作需要在月底前10天提醒用户(也就是说,在2013-09-20之前,我必须弹出消息还有10天就要到月底了)。请问有什么办法可以帮助我计算吗?因为我不能对日期使用(+, -, *, /)等运算符。现在我有一些数据如下:

<?php
    date_default_timezone_set('Asia/Phnom_Penh');
    $current = time();
    $start = 1380188957;
    echo 'Start date: '. date('Y-m-d', $start) ."\n";
    echo '<br/>';
    $repeat = 30;
    $enddate = time() + ($repeat * 24 * 60 * 60);
    echo 'end date: '. date('Y-m-d', $enddate) ."\n";

Thanks in advent for helping.


对于我的概念:如果$current小于或等于20,我想将其声明为$start的子级,并弹出消息。 - koe
嘿,Time。这些答案中有没有解决你的问题?如果有,请接受其中一个答案。 - Jeemusu
2个回答

2

并不是每个月都有31天,你可以使用php的date()函数中的t选项来获取任何一个月的天数。

// Current time as unix timestamp   
$now = time();

// Number of days in current month
$days_this_month = date("t", time());

// Last day of the current month as a unix timestamp;
$end_of_month = strtotime(date("Y-m-t", time()));

// Ten days before the end of the month as a unix timestamp
$ten_days = strtotime('-10 days', $end_of_month);

现在我们可以进行一次检查,看看是否距离月底还有10天:
if($now > $ten_days) {

    // Do something
}

0
$start = 1380188957;
$enddate = time() + ($repeat * 24 * 60 * 60);

那是你自己的代码。使用它我们可以轻松地计算出 截止日期前十天

$alert=$enddate-864000;   // That's 10 days
$alertdate=date('Y-m-d', $alert);

非常感谢您,但我需要动态的计算,而不仅仅是静态的。您能告诉我如何计算 4400 等于 10天 吗? - koe
1
1天=24小时x60分钟x60秒=86400。现在如果你要计算6天,只需将其乘以6,您就可以得到答案。但有趣的是,它已经是代码的一部分了,看那个“$repeat”行?那也做同样的事情。抱歉之前数字错了,错过了分钟数。我刚刚更新了它。 - Hanky Panky
是的,我有测试步骤,包括“10天,6天等”。感谢您的帮助,我现在会进行测试。 - koe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接