gpt4 book ai didi

php - 英语到时间

转载 作者:可可西里 更新时间:2023-11-01 12:37:53 24 4
gpt4 key购买 nike

有谁知道将英语时间表示形式转换为时间戳的好类/库?

目标是转换自然语言短语,例如“十年后”、“三周”和“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.
}

最佳答案

使用 DateTime类。

例如:

$string='four days ago';
$d=date_create($string);
$d->getTimestamp();

预计到达时间:你可以扩展:

class myDateTime extends DateTime {
static $defined_expressions=array(...);

function __construct($expression=NULL) {
if ($exp=$this->translate($expression)) {
parent::__construct($exp);
}
}

function translate($exp) {
//check to see if strtotime errors or not
//if it errors, check if $exp matches a pattern in self::$defined_expressions
return $exp, modified $exp or false
}

}

关于php - 英语到时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1826098/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com