viernes, 19 de febrero de 2016

PHP Getting yesterday date



http://stackoverflow.com/questions/6796866/php-date-yesterday


130down voteaccepted
date() itself is only for formatting, but it accepts a second parameter.
date("F j, Y", time() - 60 * 60 * 24);
To keep it simple I just subtract 24 hours from the unix timestamp.
A modern oop-approach is using DateTime
$date = new DateTime();
$date->sub(new DateInterval('P1D'));
echo $date->format('F j, Y') . "\n";
Or in your case (more readable/obvious)
$date = new DateTime();
$date->add(DateInterval::createFromDateString('yesterday'));
echo $date->format('F j, Y') . "\n";
(Because DateInterval is negative here, we must add() it here)
See also: DateTime::sub() and DateInterval
shareimprove this answer
   
Thanks for the quick response. – Alex Jul 22 '11 at 23:00
2 
very good answer, there are many ways to do it but you have the simple one, short and easy to understand ( + the OOP one for those interested in using more RAM ;) – neofutur Apr 12 '12 at 8:04
2 
@neofutur Beside "we want to waste our RAM" the OOP-approach is useful, when you already have either aDateTime-, or a DateInterval-object (or both), which may be the case in an OOP-based application (e.g. $customer->expire->add(DateInterval::createFromDateString('+1 year')) // customer paid for one additional year) Also note, that DateInterval understands ISO8601 for time intervals, but date() doesn't. At the end of course: Select the one you better fit your needs :) – KingCrunch Apr 12 '12 at 8:19 
8 
This is NOT a correct answer!! Daylight savings makes 23 and 25 hour days. So this is NOT giving you a good answer 2 hours of the year!!! – patrick Apr 24 '13 at 15:25
3 
@patrick Interesting point :) Yes, you are right, but this is only true for the first solution, not the following utilizing DateInterval. – KingCrunch Apr 25 '13 at 14:26
strtotime(), as in date("F j, Y", strtotime("yesterday"));
shareimprove this answer
10 
+1 because this makes the intent a bit more obvious when scanning through the code. Self-documenting code and all that. – Justin ᚅᚔᚈᚄᚒᚔ Jul 22 '11 at 22:48

How easy :)
date("F j, Y", strtotime( '-1 days' ) );

No hay comentarios:

Publicar un comentario