比较时间(以毫秒为单位,不带日期)


Comparing times (with milliseconds and without dates)

我正在解析字幕文件(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

要获得两个文件的同一行对话的版本,您可以检查文件2中是否有一行在文件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

你试过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
}