Reputation: 59
is it possible to add a variable string like '2 day, 2 weeks or even 4 hours' to a date time in PHP.
For example:
I have a date time like this: '2017-08-02 12:00' now the user choose an interval like '4 hours or 2 weeks' now the user choice should be added to the date time.
Is this possible?
I don't want the whole code, maybe just an advice how to do that.
thanks
Upvotes: 0
Views: 167
Reputation: 43507
Yes, use
$userDate = strtotime('2017-08-02 12:00:00');
echo date('Y-m-d H:i:s', strtotime('+4 hours', $userDate));
to get date after 4 hours
Explanation
strtotime
converts about any English textual datetime description into a Unix timestamp. Most commonly it's used with actual date string or with difference string. E.g. +5 months
, 'next Monday' and so on. It will return Unix timestamp - integer that represents how much seconds there is after 1970-01-01 (1970-01-01 00:00:00 is 0, 1970-01-01 00:01:00 is 60 and so on).
So in strtotime('2017-08-02 12:00:00')
we convert date to integer for later use.
strtotime('+4 hours', $userDate)
- here we use our date as "now" parameter (by default it's time()
) and requesting to return timestamp after 4 hours.
echo date('Y-m-d H:i:s', ...);
- date
accepts format and Unix timestamp to convert from integer back to human readable text.
Upvotes: 3
Reputation: 357
May be you are looking for this: http://php.net/manual/en/datetime.modify.php
$date = new DateTime('2006-12-12');
$date->modify('+1 day');
echo $date->format('Y-m-d');
Upvotes: 2
Reputation: 839
For a datetime you can use the add method but you have to put in the correct code for the amount to add.
$my_date = new DateTime();
$addition = 4;
$my_new_date = $my_date->add(new DateInterval("P${addition}D"));
echo $my_new_date->format('Y-m-d H:i:s');
Where addition is your variable that you want to add.
Upvotes: 0