Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I subtract 24 hour from date time object in PHP

Tags:

php

datetime

I have the following code:

  $now = date("Y-m-d H:m:s");   $date = date("Y-m-d H:m:s", strtotime('-24 hours', $now)); 

However, now it gives me this error:

A non well formed numeric value encountered in... 

why is this?

like image 306
adit Avatar asked Jul 18 '13 08:07

adit


People also ask

How does php calculate 24 hours?

php $starttime = strtotime('2017-05-11 21:00:00'); $starttimeformat = date('Y-m-d H:i:s', $starttime); echo "Current Time:"; echo $starttimeformat; echo '<br/>'; echo '<br/>'; $onedayadedtime_format = date('Y-m-d H:i:s', strtotime('+24 hours', $starttime)); echo "End Time after adding 24 hours:"; echo $ ...

How do I subtract hours from a timestamp?

To subtract hours from a given timestamp, we are going to use the datetime and timedelta classes of the datetime module. Step 1: If the given timestamp is in a string format, then we need to convert it to the datetime object. For that we can use the datetime. strptime() function.

Can I subtract dates in php?

The date_sub() function subtracts some days, months, years, hours, minutes, and seconds from a date.

What is Strtotime php?

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.


1 Answers

$date = (new \DateTime())->modify('-24 hours'); 

or

$date = (new \DateTime())->modify('-1 day'); 

(The latter takes into account this comment as it is a valid point.)

Should work fine for you here. See http://PHP.net/datetime

$date will be an instance of DateTime, a real DateTime object.

like image 102
vascowhite Avatar answered Sep 23 '22 23:09

vascowhite