2

我的代码

$time = "Tuesday, 26 June 2012";
//str_replace(',','',$time);<--this also doesn't work.
$a = strptime($time, "%l, %j %F %Y");
$stmp = mktime(0,0,0,$a['tm_mon'],$a['tm_mday'],$a['tm_year'],0);
$from_stmp = date("l, j F Y H:i:s", $stmp);
echo $from_stmp; //Tuesday, 30 November 1999 00:00:00

现在我知道有一种更优雅的方式,它确实有效:

$time = "Tuesday, 26 June 2012";
$stmp = strtotime($time);
$from_stmp = date("l, j F Y H:i:s", $stmp);
echo $from_stmp;//Tuesday, 26 June 2012 00:00:00

但是第一个版本有什么问题?我只是好奇。

4

4 回答 4

4

问题 #1

$a = strptime(time, "%l, %j %F %Y");

你写了time;它应该是$time

问题 #2

您的格式字符串错误。strptime不使用与 相同的格式字符串date,只是在前面加上百分号;它有自己的一套。您的格式字符串应如下所示:

$a = strptime($time, "%A, %e %B %Y");

问题 #3

  • strptime返回自 1900年以来的若干年。您需要添加1900.
  • strptime返回从 0 到 11 的月份。您需要添加1.

都总结了

这是您的代码,已修复:

<?php
$time = "Tuesday, 26 June 2012";
$a = strptime($time, "%A, %e %B %Y");

$stmp = mktime(0, 0, 0, $a['tm_mon'] + 1, $a['tm_mday'], 1900 + $a['tm_year'], 0);
$from_stmp = date("l, j F Y H:i:s", $stmp);
echo $from_stmp;
?>

万岁,它有效!

于 2012-06-24T20:04:33.423 回答
2

您仍然必须删除 mktime 函数的最后一个 0 它应该是正确的,

$time = "Tuesday, 26 June 2012";
$a = strptime($time, "%A, %e %B %Y");

$stmp = mktime(0, 0, 0, $a['tm_mon'] + 1, $a['tm_mday'], 1900 + $a['tm_year']);
$from_stmp = date("l, j F Y H:i:s", $stmp);
echo $from_stmp;
于 2012-06-24T20:19:41.000 回答
1

$time 的格式不对,应该是“%A, %e %B %Y”。

如果你 var_dump $a ,

array(9) {
  ["tm_sec"]=>
  int(0)
  ["tm_min"]=>
  int(0)
  ["tm_hour"]=>
  int(0)
  ["tm_mday"]=>
  int(26)
  ["tm_mon"]=>
  int(5)
  ["tm_year"]=>
  int(112)
  ["tm_wday"]=>
  int(2)
  ["tm_yday"]=>
  int(177)
  ["unparsed"]=>
  string(0) ""
}

如果您查看文档,您会发现返回的实际值。

"tm_sec"    Seconds after the minute (0-61)
"tm_min"    Minutes after the hour (0-59)
"tm_hour"   Hour since midnight (0-23)
"tm_mday"   Day of the month (1-31)
"tm_mon"    Months since January (0-11)// increment month
"tm_year"   Years since 1900// add years from 1900
"tm_wday"   Days since Sunday (0-6)
"tm_yday"   Days since January 1 (0-365)
"unparsed"  the date part which was not recognized using the specified format

你发现传递给你的 mktime 的实际值,调整你传递给 mktime 的值来解决这个问题。

<?
$time = "Tuesday, 26 June 2012";
$a = strptime($time, "%A, %e %B %Y");
var_dump($a);
$stmp = mktime(0, 0, 0, $a['tm_mon'] + 1, $a['tm_mday'], 1900 + $a['tm_year']);
$from_stmp = date("l, j F Y H:i:s", $stmp);
echo $from_stmp;
?>
于 2012-06-24T20:34:43.590 回答
0

好吧,因为strptime()已经过时了!

php 文档(PHP 5 >= 5.1.0)

所以你应该使用strtotime()...

于 2012-06-24T20:08:22.283 回答