Converting Playback Time to a Formatted String Javascript - javascript

I have a timestamp pulled from a video that I want to convert into a user-friendly string in javascript.
let now = Player.getCurrentTime();
let minutes = Math.floor(now / 60.0);
let seconds = ((now / 60.0) - minutes) * 60;
console.log(minutes+":"+(seconds < 10 ? "0":"")+seconds);
The console.log statement using the conditional operator works really nicely for quick results. Are there any basic Javascript functions that will allow me to create a string using the input as the console.log above?
UPDATE:
Quick shoutout to MrPickles
for the prompt response. I ended up just doing it manually via a helper function. If anyone needs a quick timestamp formatting, here's a quick freebie:
function formatTime(timestamp) {
let minutes = Math.floor(timestamp / 60.0);
let seconds;
let rawSeconds = ((now / 60.0) - minutes) * 60;
if(rawSeconds < 10.0) {
if(rawSeconds < 1.0) {
seconds = rawSeconds.toPrecision(2);
} else {
seconds = rawSeconds.toPrecision(3);
}
} else {
seconds = rawSeconds.toPrecision(4);
}
let mString = minutes.toString();
let sString = seconds.toString();
let displayTime = mString+":"+(seconds < 10 ? "0":"")+sString;
return displayTime;
}

In short, no.
There are date/time modules you can get to help with this but most of the popular ones are big. If this is all you are doing with the date then I would keep what you have.
If you find you are doing a lot with dates and formatting then date-fns may be an options.

Related

Subtracting Time In Javascript [duplicate]

I have two time strings like 03:01 and 01:19 . I want to subtract these two,
I tried like below,
var time1= "03:01".split(':');
var time2= "01:19".split(':');
var minutes = Math.abs(Number(time1[1])-Number(time2[1]));
var hours = Math.floor(parseInt(minutes / 60));
hours = Math.abs(Number(time1[0])-Number(time2[0])-hours);
minutes = minutes % 60;
if(hours.toString().length == 1){
hours = '0'+hours;
}
if(minutes.toString().length == 1){
minutes = '0'+minutes;
}
console.log(hours+':'+minutes);
Expected Answer -> 01:42
Actual Answer -> 02:18
Can someone tell me,where I am doing wrong ?
Using a couple of utility functions like below might help.
Basically strToMins convert string to minutes.
and minsToStr to convert back to a string.
Example below.
var time1= "03:01";
var time2= "01:19";
function strToMins(t) {
var s = t.split(":");
return Number(s[0]) * 60 + Number(s[1]);
}
function minsToStr(t) {
return Math.trunc(t / 60)+':'+('00' + t % 60).slice(-2);
}
var result = minsToStr( strToMins(time1) - strToMins(time2) );
console.log(result);

How to prevent users from cheating by adding extra seconds to a counter in JS?

I'm creating a JS counter for an exams website, I found that they can add extra time very easily in console by running sec += 10000, how can I stop this.
I'm using laravel in the backend
runCounter();
function runCounter() {
let min = 45;
let sec = min * 60;
let x = setInterval(function() {
console.log(secFormat(sec))
sec -= 1;
if (sec <= 0) {
endExam();
clearInterval(x);
}
}, 1000);
}
function secFormat(x) {
x = Number(x);
let h = Math.floor(x / 3600);
let m = Math.floor(x % 3600 / 60);
let s = Math.floor(x % 3600 % 60);
m += h * 60;
if (m < 10) {
m = "0" + m
}
if (s < 10) {
s = "0" + s
}
return m + ":" + s;
}
function endExam() {
alert('exma ended');
}
Put your function in self executing function as below
(function runCounter() {
let min = 45;
let sec = min * 60;
let x = setInterval(function() {
console.log(secFormat(sec))
sec -= 1;
if (sec <= 0) {
endExam();
clearInterval(x);
} }, 1000); }
)();
so its variables becomes private to external enviroment, i.e to console
Simple: In your Laravel project you store the time when the user started the exam and you create a cron job that will periodically run and check whether any of the exams' time elapsed. If so, then handle that exam as failed, since the user failed to send in the answers in time.
You will not need to worry then about how the user may change the JS code, since if the server is aware of when the exam has started, then it's irrelevant what the student or the browser claims.
Your main issue is that your website assumes that the user's browser has accurate information. But the user will be able to change the JS code as they please.
You can make it more difficult to your users by wrapping a function around all your Javascript, like
function() {
//your JS code
}();
in which case at least your functions will not be in global context. But that can be hacked as well.
Let me explain why you cannot prevent this from happening by any means:
One can create a small project that has the same HTML, JS as the ones you have on your site
Adding a local server that will be used as a proxy
And the user's time will simply be a constant
Even easier: The user can simply put a breakpoint somewhere in the Javascript code while he/she thinks about the solutions and then his/her time will never pass.
Never trust user data.

How to convert string hours to 'hh:mm:ss' format?

I'm getting my google api response for duration like 1 hour 13 minutes i need to covert this to 'hh:mm:ss' format.How to convert this in React js?
response:
distance: {text: "47.8 km", value: 47790}
duration:
text: "1 hour 13 mins"
value: 4378
__proto__: Object
status: "OK"
It seems the values that are provided: 44790 and 4378, are meters and seconds. Now that you have the seconds as a number you can do all sort of things to get them in the format you want. There are a lot of javascript snippets out there that can do this for you:
function convertHMS(value) {
const sec = parseInt(value, 10); // convert value to number if it's string
let hours = Math.floor(sec / 3600); // get hours
let minutes = Math.floor((sec - (hours * 3600)) / 60); // get minutes
let seconds = sec - (hours * 3600) - (minutes * 60); // get seconds
// add 0 if value < 10
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return hours+':'+minutes+':'+seconds; // Return is HH : MM : SS
}
const yourTime = convertHMS(4378); // 4378 seconds
// yourTime is 01:12:58
console.log(yourTime);
If you have a basic/beginning Javascript knowledge the only thing that might be funny business in this script are Math.floor() and parseInt().
credits to: https://www.4codev.com/javascript/convert-seconds-to-time-value-hours-minutes-seconds-idpx6943853585885165320.html in this case, you can find these ~10 lines anywhere though, I found them here after a few seconds of searching.
Always try to fix your problem in plain JS first before adding some sort of library that does the work for you, because you don't want to add a complete library for something that can be done in ~10 lines of plain JS. And ofcourse, plain JS works perfectly well in React =).
If you need to support IE6 - IE10 you might want to replace const and let with var (though I do not encourage supporting those browser if you don't have to from a business perspective).
edit: I'm fairly new to answering questions here so I converted the code to a code snippet.
Great solution, Sapulidi. I used your code with a slight modification. Posting for anyone interested.
In typescript
Hours only appear if there are >0 hours
const millisecondsToHHMMSS = (duration: number) => {
const sec = Math.round(duration / 1000);
const hours = Math.floor(sec / 3600); // get hours
const minutes = Math.floor((sec - hours * 3600) / 60); // get minutes
const seconds = sec - hours * 3600 - minutes * 60; // get seconds
// add 0 if value < 10
let sHours = hours > 0 ? `${hours}:` : '';
let sMinutes = `${minutes}`;
let sSeconds = `${seconds}`;
if (minutes < 10) {
sMinutes = '0' + sMinutes;
}
if (seconds < 10) {
sSeconds = '0' + sSeconds;
}
return sHours + sMinutes + ':' + sSeconds;
// Return is HH:MM:SS
};
let timeWithHours = 12345
let formattedWithHours = millisecondsToHHMMSS(timeWithHours)
let timeWithoutHours = 12345678
let formattedWithoutHours = millisecondsToHHMMSS(timeWithoutHours)
console.log(formattedWithHours)
console.log(formattedWithoutHours)
It is not related to React. You can simply use moment.js
moment(distance.value).format('hh:mm:ss');
You could either use one of the date formatting libraries (e.g. momentjs or date-fns) or just calculate it by yourself. You are getting the duration in seconds (it seems to be 4378 seconds), so calculating it by yourself won't be much of an effort.
Here is an example:
const values = getHoursMinutesAndSeconds(4378);
console.log(values);
console.log(`${zeroPadding(values.hours, 2)}:${zeroPadding(values.minutes, 2)}:${zeroPadding(values.seconds, 2)}`);
function getHoursMinutesAndSeconds (totalSeconds) {
// step 1: create seconds and hoursAndMinutes (minutes, but might be larger than 60)
const hoursAndMinutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
// step 2: create minutes and hours from hoursAndMinutes
const hours = Math.floor(hoursAndMinutes / 60);
const minutes = hoursAndMinutes % 60;
return { hours, minutes, seconds };
}
function zeroPadding (number, length) {
return String(number).padStart(length, '0');
}

Convert thousands of seconds to h:mm:ss in moment.js

I've been going through the docs and I'm not sure what I'm doing wrong. I need to convert 7200 to 2:00:00. Seems easy? Some attempts:
var duration = 7200;
var display = moment().seconds(duration).format("h:mm:ss");
and...
var duration = 7200;
var display = moment.duration(duration, "seconds"); //can't chain on a format method?
The format comes back correct but the numbers are all wrong. If I use a duration of Math.round(7025.526) or 7025.526 I get 9:19:06 back.
How can I convert seconds to h:mm:ss successfully?
When you use moment().seconds(duration) it will take the current date and time, and then set the seconds component to the value (spilling over into minutes and hours). If you try it at different times you will see that the result changes.
A duration object can't be formatted as a date, because it's simply not a date. It's a length of time without any defined starting or ending point.
To convert the seconds first create an empty moment object, which will be the current date and the time 0:00:00. Then you can set the seconds, which will spill over into minutes and hours.
You would want to use H rather than h to format the hours. That avoids getting times less than an hour as 12:nn:nn instead of 0:nn:nn:
var duration = 7200;
var display = moment({}).seconds(duration).format("H:mm:ss");
let duration = seconds;
let hours = duration/3600;
duration = duration % (3600);
let min = parseInt(duration/60);
duration = duration % (60);
let sec = parseInt(duration);
if (sec < 10) {
sec = `0${sec}`;
}
if (min < 10) {
min = `0${min}`;
}
if (parseInt(hours, 10) > 0) {
return (`${parseInt(hours, 10)} : ${min} : ${sec}`)
}
return (`${min} : ${sec}`)
You can do it manually by calculating hours minutes and seconds
Using the moment-duration-format plugin:
var s = moment.duration(ms).format("h:mm:ss");
Or, just using moment:
var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");

Convert hundredths to “minutes:seconds.hundredths” in javascript

In Javascript, I need help to convert an integer with hundredths to "minutes:seconds.hundredths".
So for example, I have this: '10420' and want to display it like this: 01:44.20.
Any Ideas?
function leading0(number){ return number < 10 ? "0" : "";}
mins = parseInt((hundredths / 100) / 60)
secs = parseInt((hundredths / 100) % 60)
huns = parseInt(hundredths % 100)
output = leading0(mins) + mins + ":" + leading0(secs) + secs + "." + leading0(huns) + huns;
jsFiddle example: http://jsfiddle.net/cNu2t/
var hundredths = 10420;
var seconds = Math.floor(hundredths / 100);
var minutes = Math.floor(seconds / 60);
return minutes+":"+(seconds-minutes*60)+"."+("0"+(hundredths-seconds*100)).substr(-2);
or:
function leadingZero(n) { return ("00"+n).substr(-2); }
var hundredths = 10420;
var secs = ~~(hundreths/100);
var mins = ~~(secs/60);
return mins+":"+leadingZero(secs%60)+"."+leadingZero(hundredths%100);
Moment.js should be able to handle this based on it's pretty rich set of formatting, parsing, etc. that it offers. I don't know if you'll be doing enough additional date and/or time related stuff to make adding a 5K JavaScript library to the set of resources you download for a page, but it might be worth a look if you have other spots where you could put it to use.
I know it deals in milliseconds and you can just multiply your number by ten to get to milliseconds and then pass it through their formatting function to output what you're after I think.

Categories