2011-09-03 58 views
1

我试图解构当前的时间戳,然后使用mktime时间戳(...)来重建它这里是我到目前为止的代码。

$date =time(); 
if(!empty($_GET['month'])){ 
    if(!empty($_GET['year'])){ 
     $f = getdate($date); 
     $date = mktime($f["hours"], $f["minutes"], $f["seconds"], $_GET['month'],  
         $f["days"], $_GET['year']); 
    } 
} 

$ date被稍后使用,它仍然等于当前时间()。

+0

会发生什么? – profitphp

+0

更高的目标是什么?这可能是一个更好的方法。 –

+0

你可以使用['strtotime()'](http://php.net/manual/en/function.strtotime.php)。 –

回答

5
<?php 

$month = 2; 
$year = 11; 

echo date('F j, Y', strtotime("now"))."\n"; 
echo date('F j, Y', strtotime("$month/".date('d')."/$year")); 

?> 

输出:

2011年9月3日

2011年2月3日

http://codepad.org/NWLt7ER6

编辑

此外,至于检查输入,我将它设置为只接受数值,并验证这些。

$get_month = (int)$_GET['month']; 
$get_year = (int)$_GET['year']; // This should be a 4 digit year; no '00' - '09' to deal with 

// The year check is up to you what range you accept 
if (($get_month > 0 && $get_month <= 12) && ($get_year > 1900 && $get_year < 2100)) { 
    $get_date = strtotime("$get_month/".date('d')."/$get_year"); 
} 

您可能还希望把他们在一个函数并调用它,在对象范围内使用它,或者比$date使用更具体的全局变量名。

编辑

正如profitphp指出,使用一天,当这一天不存在推入下一个月又一个月(九月和二月没有31天):

<?php 

$month = 2; 
$day = 31; 
$year = 11; 

echo date('F j, Y', strtotime(date('m')."/$day/".date('Y')))."\n"; 
echo date('F j, Y', strtotime("$month/$day/$year")); 

?> 

输出:

2011年10月1日

2011年3月3日

http://codepad.org/RFXTze5z

2

好根据您提供的说明书:

$new_day = isset($_GET['day']) ? $_GET['day'] : date("d"); 
$new_month = isset($_GET['month']) ? $_GET['month'] : false; 
$new_year = isset($_GET['year']) ? $_GET['year'] : false; 

if ($new_month and $new_year) { 
    $date = strtotime("$new_month/$new_day/$new_year"); 
} 

我给你一些额外的东西..也许就派上用场了^^