【问题标题】:Subtracting a certain number of hours, days, months or years from date从日期减去一定数量的小时、天、月或年
【发布时间】:2011-01-23 20:35:44
【问题描述】:

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

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

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

【问题讨论】:

  • 给你几个测试用例:从3月31日减去1个月;从 2 月 29 日减去一年。

标签: php datetime date time timestamp


【解决方案1】:

类似这样的:

function offset hours($hours) {
    return strtotime("+$hours hours");
}

【讨论】:

    【解决方案2】:

    尝试使用datetime::sub

    文档中的示例(链接):

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

    【讨论】:

    • 如果这些对你不起作用,因为它们是 PHP5.3 中的新功能
    • 不幸的是,我有5.2.xx版本,但我会记住它!
    【解决方案3】:

    几个小时:

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

    类似的东西在几个小时和几天内都可以正常工作(在几天内使用 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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多