我的代码与strtotime的奇怪行为 [英] Strange behaviour of my code with strtotime

查看:104
本文介绍了我的代码与strtotime的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在PHP中遇到头痛日期。我从表单获取一些数据,并尝试使用ajax调用提交更新网页而不重新加载页面。



我有一个datepicker,允许选择一系列日期,所以我已经做了一个脏功能来分离开始和结束日期,并分别发布到PHP(如果选择的日期范围)。它们以这种方式形成:01/04 / 2011,08 / 04/2011



在PHP中,我有日期变量,并尝试格式化它们以执行某些数据库查询以这种方式:

  $ date_start = $ _POST ['date_start']; 
$ date_start_form = date(Y-m-d,strtotime($ date_start));

经过一些测试,我发现如果日期高到第12个月的最后一个月,然后尝试格式化,它让我回到1970-01-01。



有人知道为什么会这样吗?

解决方案

顺便提一句,解决问题的方法是不要使用/作为日期分隔符,如果 - 或。使用像08.04.2011或08-04-2011,那么欧洲方法将被假定正在使用。



如果您只能在08/04收到日期/ 2011格式,那么一个简单的str_replace会照顾它:

  $ date =08/04/2011; 
$ date = str_replace('/','.',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, //08.04.2011
echo date('Y-m-d',strtotime($ date)); // 2011-04-08


I'm having some headaches with dates in PHP. I'm getting some data from a form and trying to "submit" it with an ajax call to update the web without reloading the page.

I have a datepicker which allows to pick a range of dates and so, I've done a dirty function to separate the start and the end date and posting it to PHP separately (in case a range of dates where selected). They are formated in this way: 01/04/2011,08/04/2011

In the PHP so I have the dates variables and try to format them to perform some database queries in this ways:

$date_start = $_POST['date_start'];
$date_start_form = date("Y-m-d",  strtotime($date_start));

After some testing I have discovered that if the date is higher to day 12 of whichever month, and then try to format it, it gives me back 1970-01-01.

Does someone know why this happen?

解决方案

By the way, the way to solve the problem is to not use / as the date separator, if - or . is used like 08.04.2011 or 08-04-2011, then the European method will be assumed to be in use.

If you can only receive dates in 08/04/2011 format, then a simple str_replace will take care of it:

$date = "08/04/2011";
$date = str_replace('/','.',$date); //08.04.2011
echo date('Y-m-d',strtotime($date));  //2011-04-08

这篇关于我的代码与strtotime的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆