Reputation: 325
I have an issue in my code whereby i sometimes need to add 1 day, 2 days or sometimes even 3 days onto the current day.
I'm using
$today = strtotime('today');
then based of holidays, weekends and other parameters i may need to add days / weekdays like so
$date = strtotime('+2 weekdays', $today);
or
$date = strtotime('+2 days', $today);
However, this seems to add 24 hours onto the current time when what i need ideally is the first second of the day. Unfortunately i cannot change the today timestamp because if it is current day then its time critical, but when adding days it needs to be the first second of the new day.
Any help or understanding on this issue i personally have would be much appreciated.
Upvotes: 0
Views: 2361
Reputation: 1463
You can use a date/time formatted string as input to strtotime
to specify the time you want. If you add that as the second parameter to strtotime
that can get you the time you want.
$date = strtotime('+2 weekdays', strtotime(date('Y-m-d 00:00:00', $today));
There are easier options though. You can also just ask strtotime
for midnight.
$date = strtotime('midnight +2 weekdays');
or a specific time.
$date = strtotime('01:23 +2 weekdays');
https://strtotime.co.uk/ is a useful site for testing out the capabilities of strtotime
Upvotes: 4
Reputation: 1
$date = new DateTime();
$date->add(new DateInterval('P"your needed days"D'));
echo $date->format('Y-m-d');
eg:'P2D'
OUTPUT:::2019-01-27
in this 'P' specifies the period in the date and then you can add year(Y),month(M)and day(D) and then for time, need to specify time(T) then hour(H),min(i or M) and sec(S). refer below http://php.net/manual/en/dateinterval.format.php
Upvotes: 0
Reputation: 1201
You can subtract from result timestamp value $timestamp % (24*3600)
;
Example:
$timestamp = mt_rand(1500000000, 1600000000);
$timestamp -= $timestamp % (24*3600);
echo date('Y-m-d H:i:s', $timestamp);
P.S. But better to use DateTime
class. There is method setTime()
:
$datetime = new DateTime();
$datetime->modify('+2 day');
$datetime->setTime(0, 0, 0, 0);
$timestamp = $datetime->getTimestamp();
echo date('Y-m-d H:i:s', $timestamp);
Upvotes: 1