php - 英语到时间

标签 php time timestamp

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

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

相关文章:

bash - 如何在 Bash 脚本中包含计时器?

javascript - PHP - 像数组一样解析对象的属性

php - Bootstrap 3 Modals 通过单独的 html/php 文件包含

php - 获得Facebook喜欢计数

java - Java 中的 CPU 执行时间

java - 在android中使用系统时间函数获取时间戳?

php - 替换为 MySQL 中的 IF 条件和 LIKE 语句

c# - 统一管理时间事件的正确方法

php - PHP中两个不同时间相减

java - Hbase Put 时间戳 (Java) 和 hbase shell 时间戳