Hello i have a problem with this code. I have tried several ways but without a success to get zero before hours etc. Also I checked different topics but without a success.
var timestamp = (Date.now() + 1000 * 2 * 60 * 24 * 1) - Date.now();
timestamp /= 1000;
function component(x, v) {
return Math.floor(x / v);
}
/* last thing i tried but maybe it will help someone
Number.prototype.pad = function(size) {
var s = String(this);
while (s.length < (size || 2)) {s = "0" + s;}
return s;
};
*/
var $div = $('div');
setInterval(function () {
timestamp--;
var
hours = component(timestamp, 60 * 60),
minutes = component(timestamp, 60) % 60,
seconds = component(timestamp, 1) % 60;
$div.html(hours + ":" + minutes + ":" + seconds);
}, 1000);
DEMO : http://jsfiddle.net/5z7ahmze/1/
Thank you for your time.
You can check your variable and add a 0 before if needed :
var comp = component(timestamp, 60 * 60);
var hour = comp < 10 ? '0' + comp : comp;
You can create a function like this
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
and then
$div.html(pad(hours, 2) + ":" + pad(minutes, 2) + ":" + pad(seconds, 2));
Maybe that is what you want. Right?
EDIT
Ok, the final answer.
var interval = setInterval(function () {
timestamp--;
function addZero (number) {
var zeroedNumber = (number < 10) ? 0 + "" + number : number;
return zeroedNumber;
}
var
hours = addZero(component(timestamp, 60 * 60)),
minutes = addZero(component(timestamp, 60) % 60),
seconds = addZero(component(timestamp, 1) % 60);
$div.html(hours + ":" + minutes + ":" + seconds);
//Below, i helped you with a "stop count" handler. (:
if(hours == 0 & minutes == 0 & seconds == 1){
clearInterval(interval);
}
}, 1000);
Dinamically dding zeroes to your counter if (hour or minute or second) is < 10.
I think your code is working, if you call the pad function on the numbers:
$div.html(hours.pad() + ":" + minutes.pad() + ":" + seconds.pad());
Related
I have My Code below,
Before=document.getElementsByName("beforehr[]");
After=document.getElementsByName("afterhr[]");
MonthTotal=0
for(i=0;i<Before.length;i++){
BeforeInSeconds= // Convert Before[i].value to Seconds
AfterInSeconds= // Convert After[i].value to Seconds
MonthTotal=parseInt(MonthTotal)+ parseInt(BeforeInSeconds)+parseInt(AfterInSeconds);
}
MonthTotalHRS= // Convert MonthTotal value to Time
document.getElementById("txtMonthTotal").value=MonthTotal;
document.getElementById("Mthtotal").innerHTML=MonthTotalHRS;
I need to convert the Before Hours to Seconds, After Hours to Seconds, sum All the Seconds and convert to Time and put it into Mthtotal
Assuming that variables Before and After are arrays.
var Before = [1, 2]; //180 Secs
var After = [3, 4]; // 420 Secs
var MonthTotal=0;
function secondsToHms(d) { // Function to convert Secs to H:m:s
d = Number(d);
var h = Math.floor(d / 3600);
var m = Math.floor(d % 3600 / 60);
var s = Math.floor(d % 3600 % 60);
var hDisplay = h > 0 ? h + (h == 1 ? " hour " : " hours ") : "";
var mDisplay = m > 0 ? m + (m == 1 ? " minute " : " minutes ") : "";
var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
return hDisplay + mDisplay + sDisplay;
}
for(i=0;i<Before.length;i++)
{
BeforeInSeconds= Before[i] * 60;
AfterInSeconds= After[i] * 60;
MonthTotal=parseInt(MonthTotal)+ parseInt(BeforeInSeconds)+parseInt(AfterInSeconds);
}
console.log(MonthTotal); //600 Secs
var convertedop=secondsToHms(MonthTotal);
alert(convertedop);
You can use .split(':') to split up your time format into an array. Where index 0 is the hour, index 1 is the minutes and index 2 is the seconds. You can then convert each time unit into seconds.
Hours to seconds: hour*3600
Minutes to seconds: minutes*60
Seconds to seconds: seconds*1 so just seconds
Doing all of this will give you your total result:
var before = [...document.getElementsByName("beforehr[]")];
var after = [...document.getElementsByName("afterhr[]")];
var monthTotal = 0
for (i = 0; i < before.length; i++) {
var beforeTime = before[i].value.split(':');
var afterTime = after[i].value.split(':');
var hourSeconds = +beforeTime[0] * 3600; // Convert the hours to seconds
var minuteSeconds = +beforeTime[1] * 60; // Convert the mins to secs
var seconds = +beforeTime[2]; // No conversions needed for secs to secs
var beforeInSeconds = hourSeconds + minuteSeconds + seconds;
// The above can be compresed into one line. I'll repeat the above for the afterTime on one line as an example:
var afterInSeconds = (+afterTime[0] * 3600) + (+afterTime[1] * 60) + (+afterTime[2])
monthTotal += parseInt(beforeInSeconds) + parseInt(afterInSeconds);
}
console.log("Month total in seconds", monthTotal)
// Hours, minutes and seconds (round down)
var hrs = ~~(monthTotal / 3600);
var mins = ~~((monthTotal % 3600) / 60);
var secs = ~~monthTotal % 60;
console.log("Month total in H:M:S", hrs +':' +mins + ':' + secs);
<input type="text" value="1:0:0" name="beforehr[]" />
<input type="text" value="1:0:0" name="beforehr[]" />
<br />
<input type="text" value="4:0:0" name="afterhr[]" />
<input type="text" value="4:0:0" name="afterhr[]" />
Also, note the unary + operator is similar to parseInt (it acts a little differently however).
The ~~ is simply just a fancy way of saying Math.floor(number)
Solution Simplified
<script>
function CalOt(){
Before=document.getElementsByName("beforehr[]");
After=document.getElementsByName("afterhr[]");
TodayOt=document.getElementsByName("txtTodayOt[]");
MonthTotal=0
for(i=0;i<Before.length;i++){
//alert(TimetoSec(Before[i].value));
BeforeInSeconds=TimetoSec(Before[i].value); //Convert Before[i].value to Seconds
AfterInSeconds=TimetoSec(After[i].value);//Convert After[i].value to Seconds
Daytot=parseInt(BeforeInSeconds)+parseInt(AfterInSeconds);
TodayOt[i].value=SecToTime(Daytot);
MonthTotal=parseInt(MonthTotal)+parseFloat(Daytot);
}
MonthTotalHRS=SecToTime(MonthTotal);// Convert MonthTotal value to Time
document.getElementById("txtMonthTotal").value=MonthTotal;
document.getElementById("Mthtotal").innerHTML=MonthTotalHRS;
}
function TimetoSec(Time){
TimeSplit=Time.split(":");
HoursSeconds=TimeSplit[0]*60*60;
Minutes=TimeSplit[1]*60;
TotalSec=parseFloat(HoursSeconds)+parseFloat(Minutes)+parseFloat(TimeSplit[2]);
console.log(TotalSec+"\n");
return TotalSec;
}
function SecToTime(Seconds){
Hr=Math.floor(Seconds/(60*60));
Mn=Seconds % (60*60);
Min=Math.floor(Mn/(60));
Sec=Mn % (60);
return Hr+":"+Min+":"+Sec;
}
</script>
I just can't figure why this doesn't work for some odd values.
For example when trying to convert 22.68 to hours and minutes the output is 22:40.800000000000004 (Seconds shouldn't even appear)
if (str_HR_PER_WEEK.indexOf('.') > -1)
{
var str_HR_PER_WEEK_hrs = str_HR_PER_WEEK.substring(0 , str_HR_PER_WEEK.indexOf('.'));
var str_HR_PER_WEEK_mins = str_HR_PER_WEEK.substring(str_HR_PER_WEEK.indexOf('.') + 1);
var float_HR_PER_WEEK_mins = parseFloat("0." + (str_HR_PER_WEEK_mins), 10);
var float_HR_PER_WEEK_mins_actual = float_HR_PER_WEEK_mins * 60;
float_HR_PER_WEEK_mins_actual = float_HR_PER_WEEK_mins_actual.toString();
tables.CURRENT_EMPLOYEES.HOURS_PER_WEEK.value = getTwoDigitTime(str_HR_PER_WEEK_hrs) + ":" + getTwoDigitTime(float_HR_PER_WEEK_mins_actual);
}
else
{
tables.CURRENT_EMPLOYEES.HOURS_PER_WEEK.value = str_HR_PER_WEEK;
}
You have to ways to achieve that,
one, do the calculations yourself:
var decimalTimeString = "1.6578";
var decimalTime = parseFloat(decimalTimeString);
decimalTime = decimalTime * 60 * 60;
var hours = Math.floor((decimalTime / (60 * 60)));
decimalTime = decimalTime - (hours * 60 * 60);
var minutes = Math.floor((decimalTime / 60));
decimalTime = decimalTime - (minutes * 60);
var seconds = Math.round(decimalTime);
if(hours < 10)
{
hours = "0" + hours;
}
if(minutes < 10)
{
minutes = "0" + minutes;
}
if(seconds < 10)
{
seconds = "0" + seconds;
}
alert("" + hours + ":" + minutes + ":" + seconds);
Two, use built in function to convert to string and then to hh:mm:
var decimalTimeString = "1.6578";
var n = new Date(0,0);
n.setSeconds(+decimalTimeString * 60 * 60);
n.setMinutes(+decimalTimeString * 60);
var result = n.toTimeString().slice(0, 5);
document.write(result);
I've got a neat function to do just that:
function hoursToHHMM(hours) {
var h = String(Math.trunc(hours)).padStart(2, '0');
var m = String(Math.abs(Math.round((hours - h) * 60))).padStart(2, '0');
return h + ':' + m;
}
It handles negative values as a bonus.
Usage is trivial:
var hours = -7.33333;
console.log(hoursToHHMM(hours));
Results in: -07:20
You can play with it here: https://jsfiddle.net/r150c2me/
var currentTime = audio.currentTime | 0;
var duration = audio.duration | 0;
it works but,
it shows the audio's total length and current time in only second format
i want to convert the default second value in Minute:Second format
Try this (lightly tested):
var seconds = currentTime % 60;
var foo = currentTime - seconds;
var minutes = foo / 60;
if(seconds < 10){
seconds = "0" + seconds.toString();
}
var fixedCurrentTime = minutes + ":" + seconds;
var currentTime = audio.currentTime | 0;
var duration = audio.duration | 0;
var minutes = "0" + Math.floor(duration / 60);
var seconds = "0" + (duration - minutes * 60);
var dur = minutes.substr(-2) + ":" + seconds.substr(-2);
var minutes = "0" + Math.floor(currentTime / 60);
var seconds = "0" + (currentTime - minutes * 60);
var cur = minutes.substr(-2) + ":" + seconds.substr(-2);
You can simply write the code yourself; it's not as if it's complicated or would ever change:
function pad(num, size) {
var s = num + '';
while (s.length < size) {
s = '0' + s;
}
return s;
}
function format_seconds(secs) {
return Math.floor(secs / 60) + ':' + (pad(secs % 60, 2));
}
dropping my own answer after 5 years and 9 months.
function() {
if(this.myAudio.readyState > 0) {
var currentTime = this.myAudio.currentTime;
var duration = this.myAudio.duration;
var seconds: any = Math.floor(duration % 60);
var foo = duration - seconds;
var min: any = foo / 60;
var minutes: any = Math.floor(min % 60);
var hours: any = Math.floor(min / 60);
if(seconds < 10){
seconds = "0" + seconds.toString();
}
if(hours > 0){
this.audioDuration = hours + ":" + minutes + ":" + seconds;
} else {
this.audioDuration = minutes + ":" + seconds;
}
}
}
I used typescript, hope this helps...
I have this function that I am trying to work with. All I am trying to do is to get the values of days, hours, min and sec into the .overTime div. I want to use the same function over and over again because i have more divs in which I want to display the same values but in a diff manner.
You guys are awesome Thank You.
NowTime = new Date(); //Time Now
StartTime = new Date($('#StartTime').val());
StopTime = new Date($('#StopTime').val());
function fixIntegers(integer){
if (integer < 0)
integer = 0;
if (integer < 10)
return '0' + integer;
return '' + integer;
}
function Test( difference )
{
var toReturn = { days: 0, hours: 0, minutes: 0, seconds: 0 };
toReturn.seconds = fixIntegers(difference % 60);
difference = Math.floor(difference / 60);
toReturn.minutes = fixIntegers(difference % 60);
difference = Math.floor(difference / 60);
toReturn.hours = fixIntegers(difference % 24);
difference = Math.floor(difference / 24);
toReturn.days = fixIntegers(difference);
return toReturn;
}
function run()
{
var output = Test( Math.floor( ( NowTime - StopTime ) / 1000 ) );
$('.OverTime').html( output.days + ':' + output.hours + ':' + output.minutes + ':' + seconds);
}
setInterval(run, 1000)
FIDDLE: http://jsfiddle.net/8943U/47/
Your first problem is this:
$('.OverTime').html( output.days + ':' + output.hours + ':' + output.minutes + ':' + seconds);
Should be:
$('.OverTime').html( output.days + ':' + output.hours + ':' + output.minutes + ':' + output.seconds);
The variable seconds does not exist, you need output.seconds instead. Then your function will begin to work see here.
Your second problem is that those values are NaN, I'll leave it to you to solve that one.
Cheers!
I want to countdown timer in format of hh:mm:ss so I use this code it's convert seconds into required format but when I count down it display me NaN. Can you tell me what I am doing wrong
Here is code
<div id="timer"></div>
JS
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second parm
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
var time = hours + ':' + minutes + ':' + seconds;
return time;
}
var count = '62';
count = count.toHHMMSS();
var counter = setInterval(timer, 1000);
function timer() {
count--;
if (count <= 0) {
clearInterval(counter);
return;
}
$('#timer').html(count);
}
Here is JsFiddle link CountDown Timer
Well, let's take a look at what your code does:
Set count to the string value 62.
Convert it to HHMMSS, so now count is equal to the string 00:01:02
Start the timer.
On the first run of the timer, decrement count. Erm... count is a string, you can't decrement it. The result is not a number.
Okay, so with that out of the, way how about fixing it:
function formatTime(seconds) {
var h = Math.floor(seconds / 3600),
m = Math.floor(seconds / 60) % 60,
s = seconds % 60;
if (h < 10) h = "0" + h;
if (m < 10) m = "0" + m;
if (s < 10) s = "0" + s;
return h + ":" + m + ":" + s;
}
var count = 62;
var counter = setInterval(timer, 1000);
function timer() {
count--;
if (count < 0) return clearInterval(counter);
document.getElementById('timer').innerHTML = formatTime(count);
}
var count = '62'; // it's 00:01:02
var counter = setInterval(timer, 1000);
function timer() {
if (parseInt(count) <= 0) {
clearInterval(counter);
return;
}
var temp = count.toHHMMSS();
count = (parseInt(count) - 1).toString();
$('#timer').html(temp);
}
http://jsfiddle.net/5LWgN/17/
If you use the jquery moment plugin. If you are not using jQuery moment then you can use formatTime(seconds) function that is in the #Niet's answer https://stackoverflow.com/a/18506677/3184195
var start_time = 0;
var start_timer = null;
start_timer = setInterval(function() {
start_time++;
var formate_time = moment.utc(start_time * 1000).format('mm:ss');
$('#Duration').text(formate_time);
}, 1000);
});
function clear() {
if (start_timer) clearInterval(start_timer);
}