Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add current time to DateTime

Tags:

php

datetime

I would like to add 5 days and current time to a date, which I have in string.

$date = new DateTime('2013-11-21');
date_add($date, date_interval_create_from_date_string('5 days'));
$curtime = date('H:i:s');

How to add current time to DateTime, or is there any other better way how to do it?

like image 534
Andrew Avatar asked Oct 15 '25 23:10

Andrew


1 Answers

Just edit your last lane - I think it is the most objective solution to your problem. The rest of your code is correct.

$curtime = $date->format('Y-m-d H:i:s');

Remember that your second lane is just an alias to:

$date->add(DateInterval::createFromDateString('5 days'));

So the full code would be:

$date = new DateTime('2013-11-21');
$date->add(DateInterval::createFromDateString('5 days'));
$curtime = $date->format('Y-m-d H:i:s');

EDIT: I've just read your question again and you ask about adding current time to this date. If you want to add time, then you need to create it from current date. It's not the perfect solution, but I'm still working on it:

$now = new DateTime(date('1970-01-01 H:i:s'));
$date->add(DateInterval::createFromDateString($now->getTimestamp() . ' seconds'));
$curtime = $date->format('Y-m-d H:i:s');
echo $curtime;

EDIT2: I've corrected it much more, look at this code:

$date = new DateTime('2013-11-21');
$date->add(DateInterval::createFromDateString('5 days'));

$now = new DateTime('now');
$today = new DateTime(date('Y-m-d'));

$time = $today->diff($now);

$date->add($time);

echo $date->format('Y-m-d H:i:s');

EDIT3: And remember about time zones:

$date = new DateTime('2013-11-21', new DateTimeZone('Europe/Warsaw'));
$date->add(DateInterval::createFromDateString('5 days'));

$now = new DateTime('now', new DateTimeZone('Europe/Warsaw'));
$today = new DateTime(date('Y-m-d'), new DateTimeZone('Europe/Warsaw'));


$time = $today->diff($now);

$date->add($time);

echo $date->format('Y-m-d H:i:s');

And fiddle: http://sandbox.onlinephpfunctions.com/code/0080d18d18dd7e2fefa7dea7d961087f14ceb3df

like image 171
Kelu Thatsall Avatar answered Oct 17 '25 13:10

Kelu Thatsall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!