php convert a date to a timestamp

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-15 11:56:08

问题


I'm trying to convert 2 dates to timestamps. One is generated by php (today's date) and the other is input by the user

$today = date("d-m-y");  // 01-12-13
$start_date = "28-11-13";

$todaytimestamp = strtotime($today);
$starttimestamp = strtotime($start_date);

echo "$today > $start_date <br>$todaytimestamp > $starttimestamp";

Problem is that the result are incorrect

Result:

01-12-13 > 28-11-13 1008201600 > 1857686400

what's wrong ?


回答1:


Always use four-digit years, as using two-digit years leads to endless headaches. 13 is not treated as a year; instead, 01-12-13 and 28-11-13 are interpreted as December 13, 2001 and November 13, 2028 by PHP. See PHP's Date Formats page, under "ISO8601 Notations": "Two digit year, month and day with dashes".

If you use 2013 instead, the issues disappear:

$today = date("d-m-Y");  // 01-12-2013
$start_date = "28-11-2013";

$todaytimestamp = strtotime($today);
$starttimestamp = strtotime($start_date);

echo "$today > $start_date <br>$todaytimestamp > $starttimestamp";

Output:

01-12-2013 > 28-11-2013
1385884800 > 1385625600



回答2:


My understanding of the documentation is that you are trying to convert a readable string into a Unix based timestamp. When you attempt to convert 01-12-13 and 28-11-13 you will get undesired results because the strtotime function has no recollection of how to properly interpret these values. Something along the lines of the code below should help you out.

$today = date("jS M Y");  // 1st Dec 2013
$start_date = "28th Nov 2013";

$todaytimestamp = strtotime($today);
$starttimestamp = strtotime($start_date);

echo "$today > $start_date <br>$todaytimestamp > $starttimestamp";

output

1st Dec 2013 > 28th Nov 2013
1385877600 > 1385618400

Just adjust your code to fit within the limitations of the language and if these values are coming from a form field you should be able to quickly and easily convert them to a readable date.




回答3:


The function assumes that you start with a year (check : http://www.onlineconversion.com/unix_time.htm), change to

 $start_date = "28-11-2013"; 

This way the function knows which is the year, it takes the default foramt which is (if not misstaken) Y-d-m



来源:https://stackoverflow.com/questions/20318457/php-convert-a-date-to-a-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!