【问题标题】:Comparing times (with milliseconds and without dates)比较时间(带毫秒和不带日期)
【发布时间】:2013-06-13 14:21:49
【问题描述】:

我正在解析字幕文件(srt 格式),下面是一行对话的示例:

27
00:01:32,400 --> 00:01:34,300
Maybe they came back
for Chinese food.

时间以格式出现

hours:minutes:seconds,milliseconds

我想操纵这些时间并进行比较,但我遇到的各种 PHP 类似乎不支持毫秒。


我的问题:

我想做的一件事是解析 2 个用于同一媒体(例如同一部电影或同一电视剧集等)的字幕文件,并比较每个字幕文件的文本以获得相同的对话行。问题是同一行的开始和结束时间会稍微偏离几百毫秒。例如,以上面的行为例,在另一个字幕文件中,同一行的时间是

00:01:32,320 --> 00:01:34,160

要获得同一对话行的两个文件的版本,您可以检查文件二中是否有一行在文件一的开始和结束时间的几百毫秒内,并且应该捕获它。类似的东西。所以我需要通过添加毫秒来操纵时间,并比较这些时间。

【问题讨论】:

  • 那么您在编程时遇到的问题是什么?只是将时间戳转换为全毫秒不起作用吗? (00:01:32,320 就是 320 + 32*1000 + 1*60*1000 + 0*3600*1000...)
  • 我认为发帖者正在考虑计算秒数的分数,因此将秒数乘以 1000 并不能提供所需的精度。 PHP microtime() 函数可能是完成此任务的最佳工具。
  • 你的 PHP 版本是什么?
  • 但是他列出的时间已经是毫秒格式了……系统的微时间与这个输入转换无关。
  • @Mike'Pomax'Kamermans,非常真实。我想我正在考虑一种更抽象的方法,但是您说得对,提供的时间很可能会转换为毫秒。

标签: php date time


【解决方案1】:

假设您使用的是 PHP >=5.3(getTimestamp() 需要),这将起作用:

$unformatted_start = '00:01:32,400';
$unformatted_end = '00:01:34,300';

// Split into hh:mm:ss and milliseconds
$start_array = explode(',', $unformatted_start);
$end_array = explode(',', $unformatted_end);

// Convert hh:mm:ss to DateTime
$start  = new DateTime($start_array[0]);
$end = new DateTime($end_array[0]);

// Convert to time in seconds (PHP >=5.3 only)
$start_in_seconds = $start->getTimestamp();
$end_in_seconds = $end->getTimestamp();

// Convert to milliseconds, then add remaining milliseconds
$start_in_milliseconds = ($start_in_seconds * 1000) + $start_array[1];
$end_in_milliseconds = ($end_in_seconds * 1000) + $end_array[1];

// Calculate absolute value of the difference between start and end
$elapsed = abs($start_in_milliseconds - $end_in_milliseconds);

echo $elapsed; // 1900

【讨论】:

    【解决方案2】:

    你试过strtotime吗?

    if (strtotime($date1) > strtotime($date2)) { # date1 is after date2
        # do work here
    } 
    if (strtotime($date1) < strtotime($date2)) { #date2 is after date1
        # do other work here
    }
    

    【讨论】:

    • 用完整的日期试试微时间功能。
    • 我采用了上述解决方案。
    猜你喜欢
    • 2011-08-29
    • 2011-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多