Skip to content

Instantly share code, notes, and snippets.

@rajrajhans
Last active September 22, 2021 06:02
Show Gist options
  • Select an option

  • Save rajrajhans/a8de8f673fbbdb9e52dc148dc3b16dea to your computer and use it in GitHub Desktop.

Select an option

Save rajrajhans/a8de8f673fbbdb9e52dc148dc3b16dea to your computer and use it in GitHub Desktop.
Frames to Timecode in JavaScript, Timecode to Frames in Javascript
const FRAME_RATE = 24;
const framesToTimecode = (timeInFrames) => {
const numOfFramesPerMin = FRAME_RATE * 60;
const hours = Math.floor(timeInFrames / (numOfFramesPerMin * 60));
const minutes = Math.floor(timeInFrames / numOfFramesPerMin) % 60;
const seconds = Math.floor((timeInFrames % numOfFramesPerMin) / FRAME_RATE);
const frames = Math.floor((timeInFrames % numOfFramesPerMin) % FRAME_RATE);
const timecode = {
hours: hours,
minutes: minutes,
seconds: seconds,
frames: frames,
};
return timecode;
// Logic for parsing:
// Hours : Divide total num of frames by number of frames in one hour.
// Minutes: Divide the total num of frames by number of frames in one minute.
// This will give you the total number of minutes (for ex, it'll give 122 if time is 2h 2min).
// We don't want the hours, we just want extra mins, so modulo it by 60.
// Seconds: timeInFrames % numOfFramesPerMin removes all full minutes and returns the number of remaining frames.
// Divide that by the frame rate to convert to seconds.
// Frames : timeInFrames % numOfFramesPerMin removes all full minutes and returns the number of remaining frames.
// Take that number and modulo it by the frame rate to remove all full seconds, which leaves us with the remaining # of frames
};
const timecodeToFrames = (timecode) => {
// "timecode" should be a string of the format "hh:mm:ss:fr"
let [hours, minutes, seconds, frames] = timeString.split(':').map((x) => Number(x));
return (hours * FRAME_RATE * 60 * 60) + (minutes * FRAME_RATE * 60) + (seconds * FRAME_RATE) + frames;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment