Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DateInterval to add weeks to a DateTime object

Tags:

php

datetime

Currently my code is adding a week, but I'm using Days instead of Weeks. I've read the documentation and don't quite understand how it works.

PHP: DateInterval

# Adds 7 days to the project launch date.
$project_launch_date->add(new DateInterval('P7D'));

Instead of adding manual 7 days, how can I specify, 'add a week', or 'add n weeks'?

like image 913
sergserg Avatar asked Oct 26 '12 14:10

sergserg


People also ask

How to add time with date in php?

php $date=strtotime("tomorrow"); echo date("Y-m-d h:i:sa", $date) . "<br>"; $date=strtotime("next Sunday"); echo date("Y-m-d h:i:sa", $date) . "<br>"; $date=strtotime("+3 Months"); echo date("Y-m-d h:i:sa", $date) .

How to add days in vb net?

To add days to DateValue , you can use DateInterval. Day , DateInterval. DayOfYear , or DateInterval.

What is DateInterval in PHP?

PHP | DatePeriod getDateInterval() Function The DatePeriod::getDateInterval() function is an inbuilt function in PHP which is used to return the date interval for the given date period. Syntax: DateInterval DatePeriod::getDateInterval( void )

How can increase day in date in PHP?

You can use strtotime. $your_date = strtotime("1 day", strtotime("2016-08-24")); $new_date = date("Y-m-d", $your_date);


1 Answers

If DateInterval is unclear for you, you can use more clear modify of DateTime class.

$date = new DateTime();
$date->modify('+1 day');
$date->modify('+5 week');

I prefer to use modify, because it makes code more readable without comments

In case you prefer to use DateInterval, here is good reference: http://www.php.net/manual/en/dateinterval.construct.php

So 5 weeks will be P5W, 3 month will be P3M, 5 weeks AND 3 month P3M5W and so on.

like image 102
Vyacheslav Voronchuk Avatar answered Oct 16 '22 16:10

Vyacheslav Voronchuk