Subtracting day from date – PHP

  php

Q(Question):

I have a script that outputs ‘Today’ or ‘Yesterday’ for the date a piece of content was posted but if its the first of the month yesterday don’t work.

Is there a way to subtract one day from the date variable, the below code I’m using at the moment is:

if(date("dmY") == date("dmY", strtotime($datetimeIn)))
$datetime = 'Today @ '.date("H:i", strtotime($datetimeIn));
else if((date("d")-1).date("mY") == date("dmY", strtotime($datetimeIn)))
$datetime = 'Yesterday @ '.date("H:i", strtotime($datetimeIn));
else
$datetime = date("D jS, F Y @ H:i", strtotime($datetimeIn));

A(Answer):

Is there a way to subtract one day from the date variable

Well you don’t have a $date variable,
but as you are using unix timestamp this is -86400

A(Answer):

If I did it like this would it make it easier to subtract a date?

$date = strtotime($datetimeIn);
if(date("dmY") == date("dmY", $date))
$datetime = 'Today @ '.date("H:i", $date);
else if((date("d")-1).date("mY") == date("dmY", $date))
$datetime = 'Yesterday @ '.date("H:i", $date);
else
$datetime = date("D jS, F Y @ H:i", $date);

A(Answer):

In your code $datetime is a string.
$date is a timestamp.
$date – 86400 is one day less
But if you are comparing dates using strings, strtotime is very clever, it even understands things like ‘yesterday’ and ‘-1 day’.

A(Answer):

I get you now, I’m just a bit confused as to how I’m going wrong implementing it.

I want the current date to be subtracted by one day, so I’m using the below code but I know I’m doing it wrong but not sure what I’m missing?

else if(date("dmY")-86400 == date("dmY", $date))

or should it be:

else if(strtotime(date("dmY"))-86400 == date("dmY", $date))

A(Answer):

else if(date("dmY")-86400

You cannot subtract 86400 off the return from date() because date() returns a string

else if(strtotime(date("dmY"))-86400 == date("dmY", $date))

And here you are comparing a string to timestamp which is an integer.
If you tried doing that in C++ you would be arrested.
Try

if(date('Ymd',strtotime('yesterday')) == date("dmY", $date)))

Or

if(date('Ymd',time()-86400)) == date("dmY", $date)))

Might need a little tweaking

A(Answer):

Appreciate your help, the two solution you gave worked, I went with the second one. Thanks again for your help.

LEAVE A COMMENT