dongsha1544 2013-02-13 20:52
浏览 42
已采纳

strtotime没有以正确的格式返回

I've some some php that changes the format of the time retrieved from the database:

$selectedDate = $_GET['date'];
$formatedDate = date("Y-d-m",strtotime($selectedDate)); // Y-m-d outputs Y-d-m oddly

echo "<form name='selectedDate' action='info.php' method='GET'>";
    echo "<select name='date' onchange='this.form.submit()'>";
    echo "<option value=select>Select a Date</option>";
        while ($row = mysql_fetch_array($result))
        {
            $date = date("m-d-Y",strtotime($row['date']));          
            echo "<option>" . $date . "</option>";
        }
        echo "</select>";echo "<br />";

            echo $selectedDate; // 1.) in: 02-13-2013, 2.) in: 02-12-2013
            echo "<br />";
            echo $formatedDate; // 1.) out: 1970-01-01, 2.) out: 2013-02-12
            echo "<br />";
        echo date("Y-m-d");

    echo "<noscript>";
    echo "<input type='submit' value='Select'>";
    echo "</noscript>";
    echo "</form>";

Now, for $formatedDate, as stated, if I use Y-m-d for output, I get 2013-12-02 instead of 2013-02-12. Not to mention that even though all $selectedDate's are in m-d-Y before being formatted, it doesn't recognize them as dates. I have the feeling that it's something totally silly that I'm missing, but I just can't see it.

So my question is, why does the strtotime() reverse my month and days, and why does it not recognize all dates? Is there a better way of getting this done?

  • 写回答

2条回答 默认 最新

  • douxiaochun4964 2013-02-13 21:09
    关注

    Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

    To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.

    Please use following way

    $date = DateTime::createFromFormat('m-d-Y', '02-14-2013'); echo $date->format('Y-m-d');

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 angular开发过程中,想要读取模型文件,即图1的335行,会报404错误(如图2)。但我的springboot里配置了静态资源文件,如图3。且在该地址下我有模型文件如图4,请问该问题该如何解决呢?
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 vite打包后,页面出现h.createElement is not a function,但本地运行正常
  • ¥15 Java,消息推送配置