strtotime 没有 return 值,但它使用值作为硬编码字符串

strtotime doesn't return value while it works with value as hardcoded string

我正在从 excel 读取一些数据并将它们导入数据库。但是有一个奇怪的问题。一切正常,除了日期部分。代码部分是:

$dob = $cells[$i][6];
echo $dob.'<br>';
$timestamp = strtotime($dob);
echo 'time- '.$timestamp;
echo 'time2- '.strtotime('01-01-2000');exit;

输出为:

01-01-2000
time- time2- 946677600

我在 excel 文件中使用的值与您从输出中看到的 01-01-2000 完全相同。

我不明白为什么 strtotime 函数可以 return 硬编码字符串版本的值,但不能使用从 excel 文件读取的变量?

感谢您的帮助。

解法: 如果有人遇到同样的问题,我就是这样处理的。

$dob_temp = $cells[$i][6];
$dob_numbers = preg_replace("/[^0-9]/","",$dob_temp);
$timestamp = strtotime(substr($dob_numbers,0,2).'-'.substr($dob_numbers,2,2).'-'.substr($dob_numbers,4,4));
$dob = date('Y-m-d', $timestamp);

您从 excel 文件中检索到的字符串可能包含一些奇怪的字符 - 例如破折号而不是连字符,这会导致 strtotime.

示例:

<?php
$dob = '01―01―2000';
echo $dob.'<br>';
$timestamp = strtotime($dob);
echo 'time- '.$timestamp;
echo 'time2- '.strtotime('01-01-2000');exit;

http://codepad.org/zKIqeHhO

您可能想要清理来自文件的日期或使用类似 DateTime::createFromFormat 的方式来传递与字符串内容相匹配的格式。