April 1, 2012

Reverse whole date in php

Question by NaeemX2

OK,

i was using following code to reverse a date to use in php yesterday.

<?php
$d=date("F j Y");
$d=explode(" ", $d);
$month=$d[0];
$day=$d[1];
$year=$d[2];
<?php for ($i=10; $i>0; $i--)
{
      $date=$month."-".$day--."-".$year;
      echo $date;
?>

this was working for me till yesterday 31 March Night. but in the morning on april 1 its started printing

April-1-2012

April-0-2012

April–1-2012 April–2-2012

and so on.

this was the bad logic i used to reverse a date. i realized it soon.
i want this like following.

April-1-2012

March-31-2012

March-30-2012

March-29-2012

and so on

so how this could be possible ?

Thanks in advance.


Well, this also a logic that work perfect for me i made after post of question. but i am really thankful for all answers. that also making me many things clear.

<?php
$d=date("F j Y");
 for ($i=0; $i>-10; $i--)
 {
$date="<br>".date('F-j-Y', strtotime("+$i days"));
echo $date;
}
?>

Answer by Starx

This is probably the quickest way to do it

for($i=1; $i <= 10; $i++) {
    echo date("F j Y", time()-($i*24*60*60)); //Instead of 24*60*60 write 86400 to increase slight performance
}

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!