dtueufe82643 2018-04-07 13:31
浏览 227
已采纳

strtotime显示以前日期的当前年份

strtotime always shows current year even the date am passing is of past years. I checked with yyyy-mm-dd format and it works properly. The only problem is with my current format which is a text (20th Dec, 2016)

$sd = "20th Dec, 2016";
echo strtotime($sd);

Output : 1545354960 (which is GMT: Thursday, December 20, 2018 2:46:00 PM)

What is wrong here? what is the solution for this?

Thanks

  • 写回答

1条回答 默认 最新

  • drw85135 2018-04-07 13:39
    关注

    The strtotime() function can only convert a limited number of formats, as detailed in the Supported Date and Time Formats section in the PHP manual.

    The following note from the Date Formats page is pertinent in this case as the 2018 part of your example is interpreted as a 24-hour time value.

    Note:

    The "Year (and just the year)" format only works if a time string has already been found -- otherwise this format is recognised as HH MM.

    You could use string manipulation (e.g. use preg_replace() or str_replace() to remove the ,) to provide a date format that PHP interprets as you want. I would prefer using a regex, eg:

    $sd = "20th Dec, 2016";
    echo date("y", strtotime(preg_replace("/([\w ]+),([\w ]+)/", "$1$2", $sd)));
    

    A good alternative would be to use DateTime::createFromFormat(), with which you state exactly the format that the date string has.

    $sd = "20th Dec, 2016";
    $dt = DateTime::createFromFormat("dS M, Y", $sd);
    echo $dt->format("d-M-Y");
    echo strtotime($dt->format("d-M-Y"));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作