【发布时间】:2010-12-22 00:25:08
【问题描述】:
有谁知道将英文时间表示形式转换为时间戳的好类/库?
目标是转换自然语言短语,例如“十年后”、“三周”和“10 分钟内”,并为它们计算出最佳匹配的 unix 时间戳。
我已经编写了一些非常糟糕且未经测试的代码来继续它,但我确信那里有很棒的日历等解析器。
private function timeparse($timestring)
{
$candidate = @strtotime($timestring);
if ($candidate > time()) return $candidate; // Let php have a bash at it
//$thisyear = date("Y");
if (strpos($timestring, "min") !== false) // Context is minutes
{
$nummins = preg_replace("/\D/", "", $timestring);
$candidate = @strtotime("now +$nummins minutes");
return $candidate;
}
if (strpos($timestring, "hou") !== false) // Context is hours
{
$numhours = preg_replace("/\D/", "", $timestring);
$candidate = @strtotime("now +$numhours hours");
return $candidate;
}
if (strpos($timestring, "day") !== false) // Context is days
{
$numdays = preg_replace("/\D/", "", $timestring);
$candidate = @strtotime("now +$numdays days");
return $candidate;
}
if (strpos($timestring, "year") !== false) // Context is years (2 years)
{
$numyears = preg_replace("/\D/", "", $timestring);
$candidate = @strtotime("now +$numyears years");
return $candidate;
}
if (strlen($timestring) < 5) // 10th || 2nd (or probably a number)
{
$day = preg_replace("/\D/", "", $timestring);
if ($day > 0)
{
$month = date("m");
$year = date("y");
return strtotime("$month/$day/$year");
}
else
{
return false;
}
}
return false; // No can do.
}
【问题讨论】:
-
输入“未来三年两天五分钟”怎么样?
-
是的,就是这样。这就是我需要的。
-
“三年,两天零五分钟”和类似的应该很容易转换为 ISO8601 间隔:“P3Y2DT5M”,您可以将其提供给 DateInterval 并添加到 DateTime 对象。
-
正则表达式将无法解析这些。你需要的是一个语法解析器(野牛等),这在技术上就像创建一个迷你编译器:P
-
这是一个有趣的挑战。在我看来,如果有一组用户提交的日期数据来了解您的用户群如何表达这样的日期,那就太好了。