将天数添加到特定日期 [英] Adding days to specific day

查看:38
本文介绍了将天数添加到特定日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多示例都是关于将天数添加到今天.但是如果我有不同的起始日怎么办?

Many examples are about adding days to this day. But how to do it, if I have different starding day?

例如(不起作用):

$day='2010-01-23';

// add 7 days to the date above
$NewDate= Date('$day', strtotime("+7 days"));
echo $NewDate;

上面的例子不起作用.我应该如何通过在日期位置放置其他内容来更改起始日期?

Example above does not work. How should I change the starding day by putting something else in the place of Date?

推荐答案

对于基于您的代码的非常基本的修复:

For a very basic fix based on your code:

$day='2010-01-23';

// add 7 days to the date above
$NewDate = date('Y-m-d', strtotime($day . " +7 days"));
echo $NewDate;

如果您使用的是 PHP 5.3+,则可以使用非常方便的新 DateTime 库:

If you are using PHP 5.3+, you can use the new DateTime libs which are very handy:

$day = '2010-01-23';

// add 7 days to the date above
$NewDate = new DateTime($day);
$NewDate->add(new DateInterval('P7D');
echo $NewDate->format('Y-m-d');

我现在完全改用DateTime,因为它非常强大.您还可以在实例化时轻松指定时区,即 new DateTime($time, new DateTimeZone('UTC')).您可以使用方法 add()sub() 来更改 DateInterval 对象的日期.这是文档:

I've fully switched to using DateTime myself now as it's very powerful. You can also specify the timezone easily when instantiating, i.e. new DateTime($time, new DateTimeZone('UTC')). You can use the methods add() and sub() for changing the date with DateInterval objects. Here's documentation:

这篇关于将天数添加到特定日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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