Jump to content

i want to add a table with every date since 1900 to current


emehrkay

Recommended Posts

[code]<?php

$month=array(1=>31,2=>29,3=>31,4=>30,5=>31,6=>30,7=>31,8=>31,9=>30,10=>31,11=>30,12=>31);

$date=array();
$date['y']=1900;
$date['m']=1;
$date['d']=1;

while($date['y'] <= 2006)
{
$date['m'] = l;
while($date['m'] <= 12)
{
$date['d'] = l;
while($date['d'] <= $month[$date['d']])
{
if($month[$date['d']] == 29 && $date['m'] == 2 && $date['y']%4 != 0) $date['d']++;
else
mysql_query("INSERT INTO `dates_table` ('id','year','month','day') VALUES (NULL,$date['y'],$date['m'],$date['d'])");
$date['d']++;
}
$date['m']++;
}
$date['y']++;
}

?>[/code]

First give it a try with one year, then with five, and if everything ok with 106. I would suggest you to add set_time_limit(0) on the top to prevent timeout.

Orio.
You could do something like this.  It's not the most elegant but it will work.  Also be aware that SQL DATETIMES before 1901 don't seem to work, so I've implemented this as a string, though with tweaking you can have it in any format.

[code]
<?php

$leap = false;
for( $i=1900; $i<2007; $i++ ) // Year number
{
if( ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0) )
{
$leap = true;
}

for( $j=1; $j<13; $j++ )  // Month number
{
switch( $j )
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: // 31-day months
$days = 31;
break;
case 4:
case 6:
case 9:
case 11: // 30-day months
$days = 30;
break;
case 2: // Februray
if( $leap )
{
$days = 29;
}
else
{
$days = 28;
}
break;
}
for( $k=1; $k<=$days; $k++ )
{
$date = $i . '-' . $j . '-' . $k; // Y-M-D format.
$sql = "INSERT INTO date_table (date) VALUES ('$date')";
//
// Use whatever DB technique you're using to send the query.
//
}
}
}

?>
[/code]


Here's my take on your problem.  I use a "home-grown" loop for the dates 1/1/1900 trough 12/31/1969 and use the date() function for dates from 1/1/1970 to the present:
[code]<?php
        $days = array(31,28,31,30,31,30,31,31,30,31,30,31);
        $all_dates = array();
        $yr = 1900;
        while ($yr < 1970) {
          for($m=0;$m<count($days);$m++) {
                $nd = $days[$m];
                if ($m == 1 && $yr % 4 == 0 && $yr % 400 == 0) $nd++;
                for ($dy=1;$dy<=$nd;$dy++) {
                    $z = $m+1;
                    echo $z.'/'.$dy.'/'.$yr."\n"; }
          }
          $yr++;
        }
        $nxtd = 0;
        while($nxtd <= time()) {
          echo date('n/j/Y',$nxtd)."\n";
          $nxtd += 86400;
        }
?>[/code]

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.