subtract minutes from calculated time javascript - javascript

I need to subtract minutes from the calculated time
var calculatedTime=11.30;// hours
var subtractTime=40;//minutes
var diff=calculatedTime - subtractTime;// How to do this ??
How to do this in javascript
Thanks

Try this:
function converToMinutes(s) {
var c = s.split('.');
return parseInt(c[0]) * 60 + parseInt(c[1]);
}
function parseTime(s) {
return Math.floor(parseInt(s) / 60) + "." + parseInt(s) % 60
}
//var minutes = parseTime(EndTIme) - parseTime(StartTime);
var timeToSubtract = 40;
var startTime = converToMinutes('11.30');
var converted = parseTime(startTime - timeToSubtract);
alert(converted);
Demo here

Related

Get difference between two times with ss.[milisecond] format [duplicate]

I have this function which formats seconds to time
function secondsToTime(secs){
var hours = Math.floor(secs / (60 * 60));
var divisor_for_minutes = secs % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
return minutes + ":" + seconds;
}
it works great but i need a function to turn milliseconds to time and I cant seem to understand what i need to do to this function to return time in this format
mm:ss.mill
01:28.5568
Lots of unnecessary flooring in other answers. If the string is in milliseconds, convert to h:m:s as follows:
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return hrs + ':' + mins + ':' + secs + '.' + ms;
}
If you want it formatted as hh:mm:ss.sss then use:
function msToTime(s) {
// Pad to 2 or 3 digits, default is 2
function pad(n, z) {
z = z || 2;
return ('00' + n).slice(-z);
}
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return pad(hrs) + ':' + pad(mins) + ':' + pad(secs) + '.' + pad(ms, 3);
}
console.log(msToTime(55018))
Using some recently added language features, the pad function can be more concise:
function msToTime(s) {
// Pad to 2 or 3 digits, default is 2
var pad = (n, z = 2) => ('00' + n).slice(-z);
return pad(s/3.6e6|0) + ':' + pad((s%3.6e6)/6e4 | 0) + ':' + pad((s%6e4)/1000|0) + '.' + pad(s%1000, 3);
}
// Current hh:mm:ss.sss UTC
console.log(msToTime(new Date() % 8.64e7))
Here is my favourite one-liner solution:
new Date(12345 * 1000).toISOString().slice(11, -1); // "03:25:45.000"
Method Date.prototype.toISOString() returns a string in the simplified extended ISO format (ISO 8601), which is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ. This method is supported in all modern browsers (IE9+) and Node.
This one-liner is limited to a range of one day, which is fine if you use it to format milliseconds up to 24 hours (i.e. ms < 86400000). The following code is able to format correctly any number of milliseconds (shaped in a handy prototype method):
/**
* Convert (milli)seconds to time string (hh:mm:ss[:mss]).
*
* #param Boolean seconds
*
* #return String
*/
Number.prototype.toTimeString = function(seconds) {
var _24HOURS = 8.64e7; // 24*60*60*1000
var ms = seconds ? this * 1000 : this,
endPos = ~(4 * !!seconds), // to trim "Z" or ".sssZ"
timeString = new Date(ms).toISOString().slice(11, endPos);
if (ms >= _24HOURS) { // to extract ["hh", "mm:ss[.mss]"]
var parts = timeString.split(/:(?=\d{2}:)/);
parts[0] -= -24 * Math.floor(ms / _24HOURS);
timeString = parts.join(":");
}
return timeString;
};
console.log( (12345 * 1000).toTimeString() ); // "03:25:45.000"
console.log( (123456 * 789).toTimeString() ); // "27:03:26.784"
console.log( 12345. .toTimeString(true) ); // "03:25:45"
console.log( 123456789. .toTimeString(true) ); // "34293:33:09"
function millisecondsToTime(milli)
{
var milliseconds = milli % 1000;
var seconds = Math.floor((milli / 1000) % 60);
var minutes = Math.floor((milli / (60 * 1000)) % 60);
return minutes + ":" + seconds + "." + milliseconds;
}
Why not use the Date object like this?
let getTime = (milli) => {
let time = new Date(milli);
let hours = time.getUTCHours();
let minutes = time.getUTCMinutes();
let seconds = time.getUTCSeconds();
let milliseconds = time.getUTCMilliseconds();
return hours + ":" + minutes + ":" + seconds + ":" + milliseconds;
}
https://jsfiddle.net/4sdkpso7/6/
function millisecondsToTime(millisecs){
var ms = Math.abs(millisecs) % 1000;
var secs = (millisecs < 0 ? -1 : 1) * ((Math.abs(millisecs) - ms) / 1000);
ms = '' + ms;
ms = '000'.substring(ms.length) + ms;
return secsToTime(secs) + '.' + ms;
}
Here is a filter that use:
app.filter('milliSecondsToTimeCode', function () {
return function msToTime(duration) {
var milliseconds = parseInt((duration % 1000) / 100)
, seconds = parseInt((duration / 1000) % 60)
, minutes = parseInt((duration / (1000 * 60)) % 60)
, hours = parseInt((duration / (1000 * 60 * 60)) % 24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
};
});
Just add it to your expression as such
{{milliseconds | milliSecondsToTimeCode}}
Editing RobG's solution and using JavaScript's Date().
function msToTime(ms) {
function addZ(n) {
return (n<10? '0':'') + n;
}
var dt = new Date(ms);
var hrs = dt.getHours();
var mins = dt.getMinutes();
var secs = dt.getSeconds();
var millis = dt.getMilliseconds();
var tm = addZ(hrs) + ':' + addZ(mins) + ':' + addZ(secs) + "." + millis;
return tm;
}
Prons:
simple and clean code; easy to modify for your needs
support any amount of hours (>24 hrs is ok)
format time as 00:00:00.0
You can put it into a helper file
export const msecToTime = ms => {
const milliseconds = ms % 1000
const seconds = Math.floor((ms / 1000) % 60)
const minutes = Math.floor((ms / (60 * 1000)) % 60)
const hours = Math.floor((ms / (3600 * 1000)) % 3600)
return `${hours < 10 ? '0' + hours : hours}:${minutes < 10 ? '0' + minutes : minutes}:${
seconds < 10 ? '0' + seconds : seconds
}.${milliseconds}`
}
This worked for me:
var dtFromMillisec = new Date(secs*1000);
var result = dtFromMillisec.getHours() + ":" + dtFromMillisec.getMinutes() + ":" + dtFromMillisec.getSeconds();
JSFiddle
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
export function getFormattedDateAndTime(startDate) {
if (startDate != null) {
var launchDate = new Date(startDate);
var day = launchDate.getUTCDate();
var month = monthNames[launchDate.getMonth()];
var year = launchDate.getFullYear();
var min = launchDate.getMinutes();
var hour = launchDate.getHours();
var time = launchDate.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true });
return day + " " + month + " " + year + " - " + time + "" ;
}
return "";
}
function msToTime(s) {
var d = new Date(s);
var datestring = ("0" + d.getDate()).slice(-2) + "-" + ("0"+(d.getMonth()+1)).slice(-2) + "-" +
d.getFullYear() + " "
+ ("0" + d.getHours()).slice(-2)
+ ":" + ("0" + d.getMinutes()).slice(-2)
+ ":" + ("0" + d.getSeconds()).slice(-2)
+"."+d.getMilliseconds();
return datestring;
}
output
16-10-2019 18:55:32.605
var
/**
* Parses time in milliseconds to time structure
* #param {Number} ms
* #returns {Object} timeStruct
* #return {Integer} timeStruct.d days
* #return {Integer} timeStruct.h hours
* #return {Integer} timeStruct.m minutes
* #return {Integer} timeStruct.s seconds
*/
millisecToTimeStruct = function (ms) {
var d, h, m, s;
if (isNaN(ms)) {
return {};
}
d = ms / (1000 * 60 * 60 * 24);
h = (d - ~~d) * 24;
m = (h - ~~h) * 60;
s = (m - ~~m) * 60;
return {d: ~~d, h: ~~h, m: ~~m, s: ~~s};
},
toFormattedStr = function(tStruct){
var res = '';
if (typeof tStruct === 'object'){
res += tStruct.m + ' min. ' + tStruct.s + ' sec.';
}
return res;
};
// client code:
var
ms = new Date().getTime(),
timeStruct = millisecToTimeStruct(ms),
formattedString = toFormattedStr(timeStruct);
alert(formattedString);
var secondsToTime = function(duration) {
var date = new Date(duration);
return "%hours:%minutes:%seconds:%milliseconds"
.replace('%hours', date.getHours())
.replace('%minutes', date.getMinutes())
.replace('%seconds', date.getSeconds())
.replace('%milliseconds', date.getMilliseconds());
}
try this function :-
function msToTime(ms) {
var d = new Date(null)
d.setMilliseconds(ms)
return d.toLocaleTimeString("en-US")
}
var ms = 4000000
alert(msToTime(ms))
A possible solution that worked for my case. It turns milliseconds into hh:ss time:
function millisecondstotime(ms) {
var x = new Date(ms);
var y = x.getHours();
if (y < 10) {
y = '0' + y;
}
var z = x.getMinutes();
if (z < 10) {
z = '0' + z;
}
return y + ':' + z;
}
This is the solution I got and working so good!
function msToHuman(duration) {
var milliseconds = parseInt((duration%1000)/100)
seconds = parseInt((duration/1000)%60)
minutes = parseInt((duration/(1000*60))%60)
hours = parseInt((duration/(1000*60*60))%24);
return hours + "hrs " minutes + "min " + seconds + "sec " + milliseconds + 'ms';
}
Most of the answers don't cover cases where there is more than 24h. This one does.
I suggest extending Date object:
class SuperDate extends Date {
get raceTime() {
return Math.floor(this/36e5).toString().padStart(2,'0')
+ this.toISOString().slice(13, -1)
}
}
console.log('marathon', new SuperDate(11235200).raceTime)
console.log('ironman', new SuperDate(40521100).raceTime)
console.log('spartathlon', new SuperDate(116239000).raceTime)
console.log('epoch', new SuperDate(new Date()).raceTime)
This approach works great with Firestore Timestamp objects which are similar to what you need:
class SuperDate extends Date {
fromFirestore (timestamp) {
return new SuperDate(timestamp.seconds * 1000 + timestamp.nanoseconds / 1000000)
}
get raceTime() {
return Math.floor(this/36e5).toString().padStart(2,'0')
+ this.toISOString().slice(13, -1)
}
}
const timestamp = {seconds: 11235, nanoseconds: 200000000}
console.log('timestamp', new SuperDate().fromFirestore(timestamp))
console.log('marathon', new SuperDate().fromFirestore(timestamp).raceTime)
Simplest Way
let getTime = (Time)=>{
let Hours = Time.getHours();
let Min = Time.getMinutes();
let Sec = Time.getSeconds();
return `Current time ${Hours} : ${Min} : ${Sec}`;
}
console.log(getTime(new Date()));
An Easier solution would be the following:
var d = new Date();
var n = d.getMilliseconds();

How can I do sum two time values in javascript

I've been trying to implement the function that sums two values as hours.
"Example: 01:30 + 00:30 = 02:00"
So I have this function below that works only if the sum of the two values is equal to a round number such as the example above. But the problem is when the values are say 01:45 + 00:20 it gives me 33:05 instead of 02:05.
I've tried several combinations but nothing has worked so far.
function sumOFHoursWorked(){
var time1 = "00:45";
var time2 = "01:20";
var hour=0;
var minute=0;
var second=0;
var splitTime1= time1.split(':');
var splitTime2= time2.split(':');
hour = parseInt(splitTime1[0])+parseInt(splitTime2[0]);
minute = parseInt(splitTime1[1])+parseInt(splitTime2[1]);
hour = hour + minute/60;
minute = minute%60;
second = parseInt(splitTime1[2])+parseInt(splitTime2[2]);
minute = minute + second/60;
second = second%60;
var REalhourstime = ('0' + hour).slice(-2)+':'+('0' + minute).slice(-2);
alert(REalhourstime);
document.getElementById('realhorasTB').innerHTML = REalhourstime;
}
It actually depends on how your time will be, i mean it will be in mm:ss formet or hh:mm:ss or maybe hh:mm:ss:msms but for just simple second and minutes you can do something like this
function sumOFHoursWorked(){
var time1 = "00:45".split(':');
var time2 = "01:20".split(':');
let secondSum = Number(time1[1]) + Number(time2[1]);
let minSum = Number(time1[0]) + Number(time2[0]);
if(secondSum > 59){
secondSum = Math.abs(60 - secondSum);
minSum += 1;
}
if(secondSum < 10){
secondSum = `0${secondSum}`;
}
if(minSum < 10){
minSum = `0${minSum}`;
}
return `${minSum}:${secondSum}`;
}
console.log(sumOFHoursWorked());
I would convert it to minutes and subtract and then calculate hours and minutes.
function totalMinutes (time) {
var parts = time.split(":")
return +parts[0] * 60 + +parts[1]
}
function timeDiff (time1, time2) {
var mins1 = totalMinutes(time1)
var mins2 = totalMinutes(time2)
var diff = mins2 - mins1
var hours = '0' + (Math.floor(diff/60))
var minutes = '0' + (diff - hours * 60)
return (hours.slice(-2) + ':' + minutes.slice(-2))
}
console.log(timeDiff("00:45", "01:20"))
It will fail for times that go over midnight, a simple less than check can fix that.
function totalMinutes (time) {
var parts = time.split(":")
return +parts[0] * 60 + +parts[1]
}
function timeDiff (time1, time2) {
var mins1 = totalMinutes(time1)
var mins2 = totalMinutes(time2)
if (mins2 < mins1) {
mins2 += 1440
}
var diff = mins2 - mins1
var hours = '0' + (Math.floor(diff/60))
var minutes = '0' + (diff - hours * 60)
return (hours.slice(-2) + ':' + minutes.slice(-2))
}
console.log(timeDiff("23:45", "00:45"))
First of all, the time1 and time2 strings are missing the seconds at the end. For example, var time1 = "00:45:00". Otherwise, your calculation will have some NaN values.
The main issue is that hour is a floating point number (~ 2.083333333333333), so ('0' + hour) is '02.083333333333333'.
You could use something like this instead: ('0' + Math.floor(hour)).

Lost trying to create a stopwatch

I'm trying to self-taugh JavaScript and while doing some texts with a stopwatch I got lost into this problem. It's working but it's always starting on 95:34:47 instead of 00:00:00
This is what i tried so far.
<script>
/*Timer Stuff*/
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}
function formatTime(time) {
var h = m = s = ms = 0;
var newTime = '';
h = Math.floor( time / (60 * 60 * 1000) );
time = time % (60 * 60 * 1000);
m = Math.floor( time / (60 * 1000) );
time = time % (60 * 1000);
s = Math.floor( time / 1000 );
ms = time % 1000;
newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 3);
return newTime;
}
function update() {
var d = new Date();
var n = d.getTime();
document.getElementById("time").innerHTML = formatTime(n);
}
function start() {
MyVar = setInterval(update, 1);
}
</script>
</head>
<body>
<div>Time: <span id="time"></span></div>
<input type="button" value="start" onclick="start();">
</body>
I understand that I need to subtract an specific amount of time to match the timer accurately, however I can't figure out how to do it.
You need to store a variable with the start time, and subtract from that. The 95 you're getting for the hours is actually much higher, just being cropped, being that you're calculating from the Unix epoch.
I would just do it something like this:
function update() {
var d = new Date();
var n = d - startTime;
document.getElementById("time").innerHTML = formatTime(n);
}
function start() {
startTime = new Date();
MyVar = setInterval(update, 1);
}
Note that you don't even need to use d.getTime() when subtracting -- you can just subtract Date objects themselves.
You have to introduce a start-time variable.
In every update-step you have to get the difference from start to now.
For your code:
<script>
/*Timer Stuff*/
timestart = new Date();
timestart_time = timestart.getTime();
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}
function formatTime(time) {
time = time -timestart_time;
var h = m = s = ms = 0;
var newTime = '';
h = Math.floor( time / (60 * 60 * 1000) );
time = time % (60 * 60 * 1000);
m = Math.floor( time / (60 * 1000) );
time = time % (60 * 1000);
s = Math.floor( time / 1000 );
ms = time % 1000;
newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 3);
return newTime;
}
function update() {
var d = new Date();
var n = d.getTime();
document.getElementById("time").innerHTML = formatTime(n);
}
function start() {
MyVar = setInterval(update, 1);
}
</script>
</head>
<body>
<div>Time: <span id="time"></span></div>
<input type="button" value="start" onclick="start();">
</body>
That works for me :)

calculate time difference between two date in HH:MM:SS javascript

I have created one timer application in javascript.
Firstly it takes the current UTC date to init timer with some reference. here's the code
on_timer: function(e) {
var self = this;
if ($(e.target).hasClass("pt_timer_start")) {
var current_date = this.get_current_UTCDate();
this.project_timesheet_db.set_current_timer_activity({date: current_date});
this.start_interval();
this.initialize_timer();
this.$el.find(".pt_timer_start,.pt_timer_stop").toggleClass("o_hidden");
Now, Once timer is started and after some time span timer has some elapsed time with reference to above on_timer: function(e) function.
This function is
start_interval: function() {
var timer_activity = this.project_timesheet_db.get_current_timer_activity();
var self = this;
this.intervalTimer = setInterval(function(){
self.$el.find(".pt_duration").each(function() {
var el_hour = $(this).find("span.hours");
var el_minute = $(this).find("span.minutes");
var minute = parseInt(el_minute.text());
if(minute >= 60) {
el_hour.text(_.str.sprintf("%02d", parseInt(el_hour.text()) + 1));
minute = 0;
}
el_minute.text(_.str.sprintf("%02d", minute));
var el_second = $(this).find("span.seconds");
var seconds = parseInt(el_second.text()) + 1;
if(seconds > 60) {
el_minute.text(_.str.sprintf("%02d", parseInt(el_minute.text()) + 1));
seconds = 0;
}
el_second.text(_.str.sprintf("%02d", seconds));
});
}, 1000);
},
Now, considering el_hour, el_minute, el_seconds How to can i count time difference between init time and current timer value in HH:MM:SS manner.
thanks in advance for help
To convert H:M:S to seconds, you can use a simple function like:
// Convert H:M:S to seconds
// Seconds are optional (i.e. n:n is treated as h:s)
function hmsToSeconds(s) {
var b = s.split(':');
return b[0]*3600 + b[1]*60 + (+b[2] || 0);
}
Then to convert seconds back to HMS:
// Convert seconds to hh:mm:ss
// Allow for -ve time values
function secondsToHMS(secs) {
function z(n){return (n<10?'0':'') + n;}
var sign = secs < 0? '-':'';
secs = Math.abs(secs);
return sign + z(secs/3600 |0) + ':' + z((secs%3600) / 60 |0) + ':' + z(secs%60);
}
var a = '01:43:28';
var b = '12:22:46';
console.log(secondsToHMS(hmsToSeconds(a) - hmsToSeconds(b))); // -10:39:18
console.log(secondsToHMS(hmsToSeconds(b) - hmsToSeconds(a))); // 10:39:18
You may want to abbreviate the function names to say:
toHMS(toSec(a) - toSec(b)); // -10:39:18
Note that this doesn't cover where the time may cross a daylight saving boundary. For that you need fully qualified dates that include the year, month and day. Use the values to create date objects, find the difference, convert to seconds and use the secondsToHMS function.
Edit
The question title mentions dates, however the content only seems to mention strings of hours, minutes and seconds.
If you have Date objects, you can get the difference between them in milliseconds using:
var diffMilliseconds = date0 - date1;
and convert to seconds:
var diffSeconds = diffMilliseconds / 1000;
and present as HH:MM:SS using the secondsToHMS function above:
secondsToHMS((date0 - date1) / 1000);
e.g.
var d0 = new Date(2014,10,10,1,43,28);
var d1 = new Date(2014,10,10,12,22,46);
console.log( secondsToHMS((d0 - d1) / 1000)); // -10:39:18
I think there is a simpler solution.
function dateDiffToString(a, b){
// make checks to make sure a and b are not null
// and that they are date | integers types
diff = Math.abs(a - b);
ms = diff % 1000;
diff = (diff - ms) / 1000
ss = diff % 60;
diff = (diff - ss) / 60
mm = diff % 60;
diff = (diff - mm) / 60
hh = diff % 24;
days = (diff - hh) / 24
return days + ":" + hh+":"+mm+":"+ss+"."+ms;
}
var today = new Date()
var yest = new Date()
yest = yest.setDate(today.getDate()-1)
console.log(dateDiffToString(yest, today))
const dateDiffToString = (a, b) => {
let diff = Math.abs(a - b);
let ms = diff % 1000;
diff = (diff - ms) / 1000;
let s = diff % 60;
diff = (diff - s) / 60;
let m = diff % 60;
diff = (diff - m) / 60;
let h = diff;
let ss = s <= 9 && s >= 0 ? `0${s}` : s;
let mm = m <= 9 && m >= 0 ? `0${m}` : m;
let hh = h <= 9 && h >= 0 ? `0${h}` : h;
return hh + ':' + mm + ':' + ss;
};
This may be the simple answer
var d1 = new Date(2014,10,11,1,43,28);
var d2 = new Date(2014,10,11,2,53,58);
var date = new Date(d2-d1);
var hour = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();
var day = date.getUTCDate() - 1;
console.log(day + ":" + hour + ":" + min + ":" + sec)
More intuitive and easier to read.
function hmsToSeconds(t) {
const [hours, minutes, seconds] = t.split(':')
return Number(hours) * 60 * 60 + Number(minutes) * 60 + Number(seconds)
}
function secondsToHMS(secs) {
return new Date(secs * 1000).toISOString().substr(11, 8)
}
var startTime = '01:43:28';
var endTime = '12:22:46';
console.log(secondsToHMS(hmsToSeconds(endTime) - hmsToSeconds(startTime))); //10:39:18

Creating timecode from frames

I have a FPS (frames per second) of 30. I have a total FPS so far, lets say 1020. I want to display this as a formatted timecode, as below.
var fps = 30;
var currentFrame = 1020;
var resultString = ; // HH:MM:SS:FF
Are there any Javascript functions built in for formatting like this?
To be clear, I need the string to be formatted as such: HH:MM:SS:FF
Are you looking for a built-in JS function?..
var FF = currentFrame % fps;
var seconds = (currentFrame - FF) / fps;
var SS = seconds % 60;
var minutes = (seconds - SS) / 60;
var MM = minutes % 60;
var HH = (minutes - MM) / 60;
There you go.
It can be done in much simpler way:
function displayTime(currentFrame) {
var fps = 30;
var h = Math.floor(currentFrame/(60*60*fps));
var m = (Math.floor(currentFrame/(60*fps))) % 60;
var s = (Math.floor(currentFrame/fps)) % 60;
var f = currentFrame % fps;
return showTwoDigits(h) + ":" + showTwoDigits(m) + ":" + showTwoDigits(s) + ":" + showTwoDigits(f);
}
function showTwoDigits(number) {
return ("00" + number).slice(-2);
}
console.log("Frame 1020 will be displayed as " + displayTime(1020));
Frame 1020 will be displayed as 00:00:34:00
showTwoDigits
This help function takes a number (example: 6), adds "00" before it, which makes it a string (example: "006"). Then it slices back 2 positions from the end (will give "06").
displayTime
var h
It calculates hours by dividing the frames by 60*60*30 frames per hours. An hour has 60*60*30 frames.
var m
Minutes are calculated in the same way by dividing it by 60*30 frames per minute. But note here that this could result in a number like 80 minutes, because it is the TOTAL amount of minutes. The script has to take in account only the remainder after dividing this amount by 60. Here the modulus comes into play. 80 % 60 will give 20, the number we are looking for.
var s
In a similar way the seconds are calculated by dividing the frames by 30 frames per second and then take it modulus 60 (so that 65 seconds will be represented as 5).
Try this:
var fps = 30;
var currentFrame = 169;
var SS = Math.floor(currentFrame / fps);
var MM = Math.floor(SS / 60);
var HH = Math.floor(MM / 60);
var FF = currentFrame - (SS * fps);
function pad(str, width, what, left) {
str = String(str);
what = String(what);
var w = width - str.length;
if (left) {
return (new Array(w + 1)).join(what) + str;
} else {
return str + (new Array(w + 1)).join(what);
}
}
var i,
timecode = [HH, MM, SS, FF];
for (i = 0; i < timecode.length; i += 1) {
timecode[i] = pad(timecode[i], 2, 0, true);
}
var resultString = timecode.join(':'); // HH:MM:SS:FF
you can also use the date object see here. Just make something like:
var d = new Date( yourframetime + new Date().getTime() );
var str = d.getHours()+':'+ d.getMinutes()+ ':' + d.getSeconds() + .......
than you can use all the string functions of the object, or make your own with it.
Old post, but I was using this recently and a combination of Alexander's and Lucas's code give the correct results. The checked version actually breaks on really large frame counts ( I think due to Math.floor).
Code is:
var fps = 30;
var currentFrame = 169;
var FF = currentFrame % fps;
var seconds = (currentFrame - FF) / fps;
var SS = seconds % 60;
var minutes = (seconds - SS) / 60;
var MM = minutes % 60;
var HH = (minutes - MM) / 60;
function pad(str, width, what, left) {
str = String(str);
what = String(what);
var w = width - str.length;
if (left) {
return (new Array(w + 1)).join(what) + str;
} else {
return str + (new Array(w + 1)).join(what);
}
}
var i,
timecode = [HH, MM, SS, FF];
for (i = 0; i < timecode.length; i += 1) {
timecode[i] = pad(timecode[i], 2, 0, true);
}
var resultString = timecode.join(':'); // HH:MM:SS:FF
For Anyone interested with the swift version of the showTwoDigits function, here is a working code sample:
func showTwoDigits(number:Float) -> (String){
var string = ("00" + String(format:"%.f", number))
var range = Range(start: (advance(string.endIndex, -2)), end: string.endIndex)
var cutStr = string.substringWithRange(range)
return cutStr
}
This function converts to HH:MM:SS:FF correctly :
var convertTime = function (frames, fps) {
fps = (typeof fps !== 'undefined' ? fps : 30 );
var pad = function(input) {return (input < 10) ? "0" + input : input;},
seconds = (typeof frames !== 'undefined' ? frames / fps : 0 );
return [
pad(Math.floor(seconds / 3600)),
pad(Math.floor(seconds % 3600 / 60)),
pad(Math.floor(seconds % 60)),
pad(Math.floor(frames % fps))
].join(':');
}
Demo
var convertTime = function (frames, fps) {
fps = (typeof fps !== 'undefined' ? fps : 30 );
var pad = function(input) {return (input < 10) ? "0" + input : input;},
seconds = (typeof frames !== 'undefined' ? frames / fps : 0 );
return [
pad(Math.floor(seconds / 3600)),
pad(Math.floor(seconds % 3600 / 60)),
pad(Math.floor(seconds % 60)),
pad(Math.floor(frames % fps))
].join(':');
}
document.body.innerHTML = '<pre>' + JSON.stringify({
5 : convertTime(5),
50 : convertTime(50),
126 : convertTime(126),
1156 : convertTime(1156),
9178 : convertTime(9178),
13555 : convertTime(13555)
}, null, '\t') + '</pre>';
See also this Fiddle.

Categories