开发者

PHP Date/Time and mktime

开发者 https://www.devze.com 2023-01-18 22:05 出处:网络
Hopefully someone can tell me whats going on with this little debugging script. <?PHP // function generates the list of times for

Hopefully someone can tell me whats going on with this little debugging script.

<?PHP
// function generates the list of times for
function generateTimes($date) { 

 $currentDate = $date; 
 echo "RECEIVED CURRENT DATE: " . 开发者_StackOverflow中文版date("m/d/Y g:iA", $currentDate) . "<br /><br />"; 

 for($i = 0; $i < 48; $i++) { 
  echo date("g:iA", $currentDate) . "<br />"; 
  $currentDate = mktime(date("g", $currentDate),date("i", $currentDate)+30,0,date("m", $currentDate),date("d", $currentDate),date("Y", $currentDate)); // 30 minutes
 } 

} 
if (isset($_POST['generate_date'])) { 
 echo "Date Stamp: " . strtotime($_POST['date']) . "<br /><br />";
 echo "The time you entered: " . date("r", strtotime($_POST['date'])) . "<br /><br />"; 
 generateTimes($_POST['date']); 

} 
echo "<form method=post action='timestampgen.php'>";
echo "<input type=text name='date' />"; 
echo "<input type=submit name='generate_date' value='Generate Time Stamp' />"; 
echo "</form><br /><br />"; 

?>

I submit a date such as 10/1/10 12:00AM and I want it to generate 30 minute intervals of time.. but it doesnt seem to be working, and I think it is related to my mktime parameters

I've been working on something all day, so this is probably me going crazy.


How about using strtotime():

function generateTimes($date) {
    // convert to timestamp (make sure to validate the $date value)
    $currentDate = strtotime($date);

    for ($i=0; $i<48; $i++) {
        echo date("g:iA", $currentDate) . "<br />"; 
        $currentDate = strtotime('+30 minutes', $currentDate);
    }
}


Once you have the current time, all you need to do is add 1800 (30 minutes times 60 seconds) to the datestamp value to move it ahead a half-hour; there's no need to monkey with mktime() over and over again.


start = new DateTime('10/1/10 12:00AM');
$interval = new DateInterval('PT30M');

foreach(new DatePeriod($start, $interval, 48) as $time)
{
        echo $time->format('Y-m-d g:iA')."\n";
}

Yields:

2010-10-01 12:00AM
2010-10-01 12:30AM
2010-10-01 1:00AM
2010-10-01 1:30AM
...
2010-10-01 11:30PM
2010-10-02 12:00AM

You can pass DatePeriod::EXCLUDE_START_DATE as the fourth parameter to DatePeriod's constructor to skip the first entry.


<?  
 $currentDate = $date;  
 echo "RECEIVED CURRENT DATE: " . date("m/d/Y g:iA", strtotime($currentDate));    

 for($i = 0; $i < 48; $i++) {  
   $currentDate= date("m/d/Y g:iA",strtotime("$currentDate +30 minutes"));  
   echo $currentDate."<br/>";  
 }  
?>  
0

精彩评论

暂无评论...
验证码 换一张
取 消