How to turn seconds (of one day) into text? - javascript

I have made this formula to turn a time as string into seconds (as integer)
seperated = new Date().split(":");
seconds = seperated[0] * 60 * 60 + seperated[1] * 60 + seperated[2];
How can I do this the reverse way?
I'm not very good at mathematics :)
EDIT:
I tried this: (the function makeTime(...) works)
function makeTime(timestr) {
var seperated = timestr.split(":");
return seperated[0] * 60 * 60 + seperated[1] * 60 + seperated[2];
}
function timeStr(integ) {
var hours = integ / 3600;
var minutes = (integ % 3600) / 60;
var seconds = integ % 60;
return hours + ":" + minutes + ":" + seconds;
}

Assuming time is the number of seconds as an integer:
hours = Math.floor(time/3600)
minutes = Math.floor((time % 3600) / 60)
seconds = time % 60
timeString = hours + ':' + minutes + ':' + seconds

You can use datejs, and write a code some thing like follows
(new Date).clearTime()
.addSeconds(15457)
.toString('H:mm:ss');
EDIT:
Or
hours = totalSeconds / 3600;
totalSeconds %= 3600;
minutes = totalSeconds / 60;
seconds = totalSeconds % 60;

Related

Set a GMT on a countdown script

How can I set a GMT to date.Now()?
var countDownDate = getNextDayOfWeek(new Date(),0,21);
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24)).toString();
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString();
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)).toString();
var seconds = Math.floor((distance % (1000 * 60)) / 1000).toString();
// Add 0 when value are < 10
hours = (hours < 10) ? "0"+hours : hours;
minutes = (minutes < 10) ? "0"+minutes : minutes;
seconds = (seconds < 10) ? "0"+seconds : seconds;
var grb = jq("#grb");
// Display the result in the element with id="grb"
grb.html(days + "d " + hours + "h " + minutes + "m " + seconds + "s");
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
var one_hour = -60 * -60 * -1000;
if(distance < one_hour){
grb.html("GRB is finished!");
}else{
grb.html("GRB is open!");
}
}
}, 1000);
});
It keeps using the time of your computer, and I want to use a timezone to be stored everytime.
I have tried TimeZoneOffset, didn't worked, any help would be appreciated.
please see this
var now = new Date();
var nowUTC = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
var distance = end - nowUTC;

Dynamic JavaScript time counter

I'm trying to make a dynamic time counter/timer in JavaScript.
Why dynamic? Well I would like to display days/hours/minutes/seconds if the time stamp is bigger enough to display days or hours and so on.
In case the timestamp is less than a day I would like that the script dynamically displays only the hours.
1D 0H 59M 59S
23H 59M 59S
59M 59S
59S
MESSAGE
Here is the code I try to make it work.
<center>
<script>
var countDownDate = new Date("2017-11-17T20:10:30Z").getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
// Seconds
if (distance < 1000){
document.getElementById("count1").innerHTML = seconds + "s ";
}
// Minutes
if (distance < 60000){
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("count1").innerHTML = minutes + "m " + seconds + "s ";
}
// Hours
if (distance < 3600000){
var hours = Math.floor(distance / (1000 * 60 * 60 * 1));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("count1").innerHTML = hours + "h " + minutes + "m " + seconds + "s ";
}
// Days
if(distance > 3600001){
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("count1").innerHTML = days + "d " + hours + "h " + minutes + "m " $
}
if (distance < 0) {
clearInterval(x);
document.getElementById("count1").innerHTML = "You will be redirected now";
}
}, 1000);
</script>
<p id="count1"></p>
</center>
I think that my problem is related with math confusion in milliseconds but I can't find out what is wrong.
These changes made it work for me:
<center>
<script>
var countDownDate = new Date("2017-11-17T21:30:30Z").getTime();
var x = setInterval(function () {
var now = new Date().getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Seconds
if (distance <= 60000) {
document.getElementById("count1").innerHTML = seconds + "s ";
}
// Minutes
else if (distance <= 3600000) {
document.getElementById("count1").innerHTML = minutes + "m " + seconds + "s ";
}
// Hours
else if (distance <= 86400000) {
document.getElementById("count1").innerHTML = hours + "h " + minutes + "m " + seconds + "s ";
}
// Days
else if (distance > 86400000) {
document.getElementById("count1").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
}
if (distance < 0) {
clearInterval(x);
document.getElementById("count1").innerHTML = "You will be redirected now";
}
}, 1000);
</script>
<p id="count1"></p>
I changed the milliseconds accordingly, and in your days you had a "$" so i changed that.
I changed the date around and got the effect I think you were going for.
It looks like you're doing this the absolute hardest way possible, and also reinventing the wheel. There are a lot of great references to built in javascript functions (like MDN) that you should really take a look at.
If you're doing this as an intellectual exercise think about restructuring your code into something like this (obviously just psuedocode):
let dateHTML = "";
if (time1.seconds - time2.seconds > 0) {
dateHTML = (time1.seconds - time2.seconds) + "s";
}
if (time1.minutes-time2.minutes > 0) {
dateHTML = (time1.minutes-time2.minutes) + "m " + dateHTML;
}
//So on and so forth for the maximum interval you want to account for.
document.getElementById("count1").innerHTML = dateHTML;
You can probably get really clever with null operators, putting the time unit distances into an array to clean up the syntax and avoid doing calculations twice etc. but this should cut down on what you're doing significantly.
Do keep in mind that there are JS libraries built to do this exact sort of thing really well, so if you're working on a "real" project consider that.
Here is the whole script in working order in case somebody else need it:
The whole script is meant to be reused multiply times in a single page by changing the ID in the $FD['id'] array variable and copy pasting the function that prints/echoing the function content.
PHP FUNCTION INCLUDE FILE (count.php):
<?php
// JS Date format
// 2017-11-14T12:00:00Z
function counter($FD){
$date=$FD['date'];
$id=$FD['id'];
$display_start_1=$FD['display_start_1'];
$display_start_2=$FD['display_start_2'];
$display_end=$FD['display_end'];
echo $counter=<<<a
<center>
<script>
var countDownDate$id = new Date("$date").getTime();
var x$id = setInterval(function () {
var now$id = new Date().getTime();
var distance$id = countDownDate$id - now$id;
var days$id = Math.floor(distance$id / (1000 * 60 * 60 * 24));
var hours$id = Math.floor((distance$id % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes$id = Math.floor((distance$id % (1000 * 60 * 60)) / (1000 * 60));
var seconds$id = Math.floor((distance$id % (1000 * 60)) / 1000);
// Seconds
if (distance$id <= 60000) {
document.getElementById("count$id").innerHTML ="$display_start_1 " + seconds$id + "s " + " $display_start_2";
}
// Minutes
else if (distance$id <= 3600000) {
document.getElementById("count$id").innerHTML ="$display_start " + minutes$id + "m " + seconds$id + "s " + " $display_start_2";
}
// Hours
else if (distance$id <= 86400000) {
document.getElementById("count$id").innerHTML ="$display_start_1 " + hours$id + "h " + minutes$id + "m " + seconds$id + "s " + " $display_start_2";
}
// Days
else if (distance$id > 86400000) {
document.getElementById("count$id").innerHTML ="$display_start_1 " + days$id + "d " + hours$id + "h " + minutes$id + "m " + seconds$id + "s " + " $display_start_2";
}
if (distance$id < 0) {
clearInterval(x$id);
document.getElementById("count$id").innerHTML = "$display_end";
}
}, 1000);
</script>
<p id="count$id"></p>
a;
}
?>
PHP DISPLAY FILE (count_display.php):
<?php
$now = time();
// Simulation of utc time (-1 hour +1 minute)
// By modifying the amount of seconds you set/define the amount of seconds that will counted down
$timestamp_new=$now-3600+10;
// Time formattig for JavaScript code
$date_new=date('Y-m-d\TH:i:s\Z', $timestamp_new);
// Include the function file once only
include'count.php';
// Define variables for the first counter
$FD1['date']="$date_new";
$FD1['id']='1';
$FD1['display_start_1']="Please wait for another:<br >";
$FD1['display_start_2']="<br />We are preparing your playground for you.";
$FD1['display_end']="Your Playground is ready at:<br /><a href='http://555.555.555.555'>Game server 01</a>";
counter($FD1);
// Define variables for the second counter
$timestamp_new=$now-3600+15;
$date_new=date('Y-m-d\TH:i:s\Z', $timestamp_new);
// The second count down timer
$FD2['date']="$date_new";
$FD2['id']='2';
$FD2['display_start_1']="Please wait for another:<br >";
$FD2['display_start_2']="<br />We are preparing your playground for you.";
$FD2['display_end']="Your Playground is ready at:<br /><a href='http://100.100.100.100'>Game server 02</a>";
counter($FD2);
// And so on ....
?>
Hoping that this will save a lot of time to somebody else ;)
Have a great life (you who can and know how) ;)

timestamp countdown going in negative

I have a script that countdowns timestamp. It is working fine but the problem it keeps going less than 0 into negative. I want it to stop at zero.
// $nowtime is a date in future
var startLive = new Date("<?php echo $nowtime; ?>");
var timestamp = startLive - Date.now();
timestamp /= 1000; // from ms to seconds
function component(x, v) {
return Math.floor(x / v);
}
var $div = $('.time');
timer = setInterval(function() {
timestamp--;
var days = component(timestamp, 24 * 60 * 60),
hours = component(timestamp, 60 * 60) % 24,
minutes = component(timestamp, 60) % 60,
seconds = component(timestamp, 1) % 60;
$div.html(days + " days, " + hours + ":" + minutes + ":" + seconds);
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Output looks like 1 Days, 6:10:30
Problem is if it is less than zero it still goes in negative. something like -3 days, -3:-5:-5
How to stop at 0.
Thanks.
timer = setInterval(function() {
/* if timestamp <= 0 return means skip rest of function */
if(timestamp <= 0) {
clearInterval(timer);
return;
}
timestamp--;
var days = component(timestamp, 24 * 60 * 60),
hours = component(timestamp, 60 * 60) % 24,
minutes = component(timestamp, 60) % 60,
seconds = component(timestamp, 1) % 60;
$div.html(days + " days, " + hours + ":" + minutes + ":" + seconds);
}, 1000);
if(timestamp <= 0)
{
clearInterval(timer);
}

javascript countdown from d:h:m:s

I'm new in javascript.
My PHP script returns a value in this format
d:h:m:s
Now I would like to have a countdown which is able to countdown each second from this.
I modified a countdown. This works once a time, after the countdown "ticks" each second it returns NaN all the time. Any idea what I do wrong?
$(document).ready(function() {
setInterval(function() {
$('.countdown').each(function() {
var time = $(this).data("time").split(':');
var timestamp = time[0] * 86400 + time[1] * 3600 + time[2] * 60 + time[3] * 1;
var days = Math.floor(timestamp / 86400);
console.log(time,timestamp);
var hours = Math.floor((timestamp - days * 86400) / 3600);
var minutes = Math.floor((timestamp - hours * 3600) / 60);
var seconds = timestamp - ((days * 86400) + (hours * 3600) + (minutes * 60))-1;
$(this).data("time",""+days+":"+hours+":"+minutes+":"+seconds);
if (hours < 10) {
hours = '0' + hours;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
$(this).text(days + ':' + hours + ':' + minutes + ':' + seconds);
});
}, 1000);
})
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1 class="countdown">02:03:05:59</h1>
As far as I can see you have 2 problems here:
after the first execution you change the pattern of the text you display in the h1. First you have 02:03:05:59. Then you want to write 02 days 03:05:58 into the tag. Next time you parse it, you get the error because you split at : and that does not work anymore as you have days instead of : as the seperator for the first part.
When calculating the minutes, you should also substract the days and not just the hours.
When you wan to keep the dd:hh:mm:ss format, you could do it like this:
$(document).ready(function() {
setInterval(function() {
$('.countdown').each(function() {
var time = $(this).text().split(':');
var timestamp = time[0] * 86400 + time[1] * 3600 + time[2] * 60 + time[3] * 1;
timestamp -= timestamp > 0;
var days = Math.floor(timestamp / 86400);
console.log(days);
var hours = Math.floor((timestamp - days * 86400) / 3600);
var minutes = Math.floor((timestamp - days * 86400 - hours * 3600) / 60);
var seconds = timestamp - days * 86400 - hours * 3600 - minutes * 60;
if (days < 10) {
days = '0' + days;
}
if (hours < 10) {
hours = '0' + hours;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
$(this).text(days + ':' + hours + ':' + minutes + ':' + seconds);
});
}, 1000);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1 class="countdown">02:03:05:59</h1>
Your snippet goes from dd:hh:mm:ss to dd days, hh hours. So second time around, your tag contains non-parsable text.
I have changed it to something more precise. Something even MORE precise would be to give a timestamp in milliseconds in the future instead of something with seconds since it will take several seconds to render the page. If you round on minutes from the server, it would likely be better.
var aDay = 24*60*60*1000, anHour = 60*60*1000, aMin = 60*1000, aSec = 1000;
$(document).ready(function() {
$('.countdown').each(function() {
var time = $(this).data("time").split(':');
var date = new Date();
date.setDate(date.getDate()+parseInt(time[0],10))
date.setHours(date.getHours()+parseInt(time[1],10),date.getMinutes()+parseInt(time[2],10),date.getSeconds()+parseInt(time[3],10),0)
$(this).data("when",date.getTime());
});
setInterval(function() {
$('.countdown').each(function() {
var diff = new Date(+$(this).data("when"))-new Date().getTime();
var seconds, minutes, hours, days, x = diff / 1000;
seconds = Math.floor(x%60); x=(x/60|0); minutes = x % 60; x= (x/60|0); hours = x % 24; x=(x/24|0); days = x;
$(this).text(
days + ' day' +(days==1?", ":"s, ") +
hours + ' hour' +(hours==1?", ":"s, ") +
minutes + ' minute'+(minutes==1?", ":"s, ") +
seconds + ' second'+(seconds==1?".":"s.")
);
});
}, 500);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1 class="countdown" data-time="02:03:05:59"></h1>

How can I convert milliseconds to "hhmmss" format using javascript?

I am using javascript Date object trying to convert millisecond to how many hour, minute and second it is.
I have the currentTime in milliseconds
var currentTime = new Date().getTime()
and I have futureTime in milliseconds
var futureTime = '1432342800000'
I wanted to get difference in millisecond
var timeDiff = futureTime - currentTime
the the timeDiff was
timeDiff = '2568370873'
I want to know how many hours, minutes, seconds it is.
Could anyone help?
const secDiff = timeDiff / 1000; //in s
const minDiff = timeDiff / 60 / 1000; //in minutes
const hDiff = timeDiff / 3600 / 1000; //in hours
updated
function msToHMS( ms ) {
// 1- Convert to seconds:
let seconds = ms / 1000;
// 2- Extract hours:
const hours = parseInt( seconds / 3600 ); // 3,600 seconds in 1 hour
seconds = seconds % 3600; // seconds remaining after extracting hours
// 3- Extract minutes:
const minutes = parseInt( seconds / 60 ); // 60 seconds in 1 minute
// 4- Keep only seconds not extracted to minutes:
seconds = seconds % 60;
alert( hours+":"+minutes+":"+seconds);
}
const timespan = 2568370873;
msToHMS( timespan );
Demo
If you are confident that the period will always be less than a day you could use this one-liner:
new Date(timeDiff).toISOString().slice(11,19) // HH:MM:SS
N.B. This will be wrong if timeDiff is greater than a day.
Convert ms to hh:mm:ss
function millisecondsToHuman(ms) {
const seconds = Math.floor((ms / 1000) % 60);
const minutes = Math.floor((ms / 1000 / 60) % 60);
const hours = Math.floor((ms / 1000 / 3600 ) % 24)
const humanized = [
pad(hours.toString(), 2),
pad(minutes.toString(), 2),
pad(seconds.toString(), 2),
].join(':');
return humanized;
}
=
function msToHMS( 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 ;
}
Converts milliseconds to a string in the format hh:mm:ss. Here's my version:
function HHMMSSFromMilliseconds(ms) {
// 1- Convert to seconds:
var seconds = ms / 1000;
// 2- Extract hours:
var hours = parseInt(seconds / 3600); // 3600 seconds in 1 hour
seconds = parseInt(seconds % 3600); // extract the remaining seconds after extracting hours
// 3- Extract minutes:
var minutes = parseInt(seconds / 60); // 60 seconds in 1 minute
// 4- Keep only seconds not extracted to minutes:
seconds = parseInt(seconds % 60);
// 5 - Format so it shows a leading zero if needed
let hoursStr = ("00" + hours).slice(-2);
let minutesStr = ("00" + minutes).slice(-2);
let secondsStr = ("00" + seconds).slice(-2);
return hoursStr + ":" + minutesStr + ":" + secondsStr
}
let timespan = 23570 * 1000;
let formattedTime = HHMMSSFromMilliseconds(timespan);
console.log(formattedTime);
Convert millis to DD(days):HH:MM:SS
function formatTime(timeMS) {
const [MS_IN_SEC, SEC_IN_DAY, SEC_IN_HOUR, SEC_IN_MIN] = [1000, 86400, 3600, 60];
let seconds = Math.round(Math.abs(timeMS) / MS_IN_SEC);
const days = Math.floor(seconds / SEC_IN_DAY);
seconds = Math.floor(seconds % SEC_IN_DAY);
const hours = Math.floor(seconds / SEC_IN_HOUR);
seconds = Math.floor(seconds % SEC_IN_HOUR);
const minutes = Math.floor(seconds / SEC_IN_MIN);
seconds = Math.floor(seconds % SEC_IN_MIN);
const [dd, hh, mm, ss] = [days, hours, minutes, seconds]
.map(item => item < 10 ? '0' + item : item.toString());
return dd + ':' + hh + ':' + mm + ':' + ss;
}
The difference in time is in milliseconds:
Get time difference between two dates in seconds
to get the difference you have to use math.floor()
http://www.w3schools.com/jsref/jsref_floor.asp
var secDiff = Math.floor(timeDiff / 1000); //in s
var minDiff = Math.floor(timeDiff / 60 / 1000); //in minutes
var hDiff = Math.floor(timeDiff / 3600 / 1000); //in hours
var timediff = futureTime - currentTime
long seconds = (long) (timediff / 1000) % 60 ;
long minutes = (long) ((timediff / (1000*60)) % 60);
long hours = (long) ((timediff / (1000*60*60)) % 24);
if(hours>0)
time = hours+" hrs : "+minutes+" mins";
else if(minutes>0)
time = minutes+" mins";
else if(seconds>0)
time = seconds+" secs";
Here is a simple function
function simplifiedMilliseconds(milliseconds) {
const totalSeconds = parseInt(Math.floor(milliseconds / 1000));
const totalMinutes = parseInt(Math.floor(totalSeconds / 60));
const totalHours = parseInt(Math.floor(totalMinutes / 60));
const days = parseInt(Math.floor(totalHours / 24));
const seconds = parseInt(totalSeconds % 60);
const minutes = parseInt(totalMinutes % 60);
const hours = parseInt(totalHours % 24);
let time = '1s';
if (days > 0) {
time = `${days}d:${hours}h:${minutes}m:${seconds}s`;
} else if (hours > 0) {
time = `${hours}h:${minutes}m:${seconds}s`;
} else if (minutes > 0) {
time = `${minutes}m:${seconds}s`;
} else if (seconds > 0) {
time = `${seconds}s`;
}
return time;
}

Categories

Resources