SRT文件时间戳转毫秒方法及时间戳标准性与Date对象转换咨询
Let’s tackle your questions one by one, starting with the handy conversion function you need for audio cross-referencing.
1. Convert SRT Timestamp to Milliseconds
Here’s a no-fuss JavaScript function built specifically for your SRT timestamp format (HH:MM:SS,mmm):
function srtTimestampToMs(timestamp) { // Swap comma to dot to align with JS's time parsing conventions const [timeSegment, msSegment] = timestamp.replace(',', '.').split('.'); const [hours, minutes, seconds] = timeSegment.split(':').map(Number); // Calculate total milliseconds return (hours * 3600 + minutes * 60 + seconds) * 1000 + parseInt(msSegment, 10); } // Quick test: const exampleMs = srtTimestampToMs('00:00:11,544'); console.log(exampleMs); // Output: 11544
This handles the SRT-specific comma separator for milliseconds and breaks down the time units into a single millisecond value—perfect for syncing with audio playback APIs.
2. Is This Timestamp a Standard Format?
Absolutely! This is the official, standardized timestamp format for SubRip (SRT) subtitle files. The SubRip spec defines timestamps as HH:MM:SS,mmm where:
HH= 2-digit hours (00-99)MM= 2-digit minutes (00-59)SS= 2-digit seconds (00-59)mmm= 3-digit milliseconds (000-999)
The comma separating seconds and milliseconds is the key difference from ISO 8601 time formats, which use a dot.
3. Can It Be Easily Converted to a Date Object?
Not directly—and here’s the context you need:
- SRT timestamps are relative time offsets (counted from the start of the audio/video file), not absolute calendar dates/times. A
Dateobject is designed to represent specific moments in time, so converting an SRT timestamp alone doesn’t have inherent meaning unless you pair it with a known start time of the media. - If you do need a Date object (e.g., to sync with a media’s broadcast timestamp), you can:
- Convert the SRT timestamp to milliseconds using the function above.
- Add that offset to the media’s absolute start
Date.
For example:
const mediaStartDate = new Date('2024-05-20T14:30:00Z'); const srtOffsetMs = srtTimestampToMs('00:00:11,544'); const syncDate = new Date(mediaStartDate.getTime() + srtOffsetMs); console.log(syncDate.toISOString()); // Output: 2024-05-20T14:30:11.544Z
If you’re just syncing with media playback, sticking with the millisecond offset is usually simpler than working with Date objects.
内容的提问来源于stack exchange,提问作者Lee Probert




