【问题标题】:Passing a UK date in a URL在 URL 中传递英国日期
【发布时间】:2014-12-19 06:28:04
【问题描述】:

我正在按照以下格式在英国格式的 URL 中传递日期:

http://www.website.com/index.php?from_date=01/04/2013&to_date=12/04/2013

日期范围为 2013 年 4 月 1 日至 2013 年 4 月 12 日。

然后我使用下面的PHP将其转换为YYYY-MM-DD格式。

<?php

$rpt_from_date = date("Y-m-d", strtotime($_GET["from_date"]) );
$rpt_to_date = date("Y-m-d", strtotime($_GET["to_date"]) );

echo $rpt_from_date;
echo "</br>";
echo $rpt_to_date;

?>

由于某种原因,这不起作用。以上返回以下内容:

2013-01-04

2013-12-04

它正在转换月份和日期。我希望它返回:

2013-04-01

2013-04-12

有人有什么想法吗?

【问题讨论】:

  • strtotime() 认为/ 分隔的日期是美国格式。您的原始 URL 需要使用例如 to_date=12-04-2013
  • 这与 URL 无关,仅与 strtotime 解析日期的方式有关。这已经回答了很多次了......
  • explode by / 并自行解析,如果strtotime 无法识别您提供的格式,则您无能为力。

标签: php date


【解决方案1】:

使用DateTime 对象,让 php 了解您将日期传递给它的格式。

$rpt_from_date = DateTime::createFromFormat('d/m/Y', $_GET["from_date"]);
echo $rpt_from_date->format('Y-m-d');

【讨论】:

    【解决方案2】:

    PHP 正在以美国格式 (MM/DD/YYYY) 读取您的时间字符串,因为您使用的是斜杠。您可以使用破折号来表示时间:index.php?from_date=01-04-2013&amp;to_date=12-04-2013,或自行转换:

    $uktime = implode("-", explode("/", $_GET['from_date']));
    

    【讨论】:

      【解决方案3】:

      我会提供解决方案,但它没有使用日期功能:

      $arr = explode("/",$_GET["from_date"]);
      $from_date = $arr[2]."-".$arr[1]."-"$arr[0];
      

      第二种解决方法如下:

      $from_date = implode(array_reverse(explode("/",$_GET["from_date"])));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-28
        • 1970-01-01
        • 2020-10-24
        相关资源
        最近更新 更多