【问题标题】:Reconstructing a timestamp with $_GET values使用 $_GET 值重建时间戳
【发布时间】:2011-09-03 18:38:34
【问题描述】:

我正在尝试解构当前时间戳,然后使用 mktime(...) 使用通过 $_GET 传递的值来重建它

到目前为止,这是我的代码。

$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 稍后使用,它仍然等于当前时间()。

【问题讨论】:

  • 更高的目标是什么?可能有比这更整洁的方法。
  • 你可以使用strtotime()
  • 请注意,例如并非所有月份都存在第 31 天……所以这样做可能会产生奇怪的结果。
  • @PhilipK 你到底想要发生什么?上面的代码应该给你一个带有当前小时、分钟、秒和天的新日期......但是指定的年份和月份?如果你想要别的东西,那么你需要相应地交换它们。
  • 我明白@profitphp 在说什么;如果您使用 8 月 31 日,但将其回溯到 2 月,我相信您将得到的结果是 3 月 2 日或 3 日。

标签: php datetime time


【解决方案1】:
<?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 指出的那样,当那一天不存在时,使用另一个月的一天会推送到下个月(9 月和 2 月没有 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");
    }
    

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

    【讨论】:

      猜你喜欢
      • 2015-02-25
      • 2015-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-24
      • 2013-07-07
      • 2012-06-30
      相关资源
      最近更新 更多