I am creating a countdown on a session that is 20 minutes. When I do a get request I get back
20.
This is fine. My next step is to set this so that it can be subtracted by
1000 milliseconds on an $interval
I have tried the following code
var d = moment.duration(x, 'milliseconds');
moment(d.asMinutes(),'mm').format('mm:ss');
Which returns
"21:00"
This is great, but the problem is now I have a string. I am not sure how I can start subtracting seconds off of this timer.
Any help would be greatly appreciated.
If you just want a session timeout there's no need to complicate things, use setTimeout:
const SESSION_MAX = 20 * 60 * 1000; // 20 min to milliseconds
setTimeout(logOutFunction, SESSION_MAX);
If for some reason you want more control, then just work with the integers returned by a Date object's native getTime:
let start = Date.now();
let end = start + (20 * 60 * 1000);
const INTERVAL = 1000; //ms
Then increment start on a clocktick and check if its >= end.
Related
var timeArr = moment().format('HH:mm:ss').split(':');
var timeInMilliseconds = (timeArr[0] * 3600000) + (timeArr[1] * 60000);
This solution works, test it, but I'd rather just use the moment api instead of using my own code.
This code returns TODAYS time in milliseconds. I need it to call another function in milliseconds...Can not use the epoch. Need today's time formated in milliseconds. 9:00am = 3.24e+7 milliseconds 9:00pm = 6.84e+7 milliseconds.
From the docs:
http://momentjs.com/docs/#/parsing/unix-timestamp-milliseconds/
So use either of these:
moment(...).valueOf()
to parse a preexisting date and convert the representation to a unix timestamp
moment().valueOf()
for the current unix timestamp
See this link http://momentjs.com/docs/#/displaying/unix-timestamp-milliseconds/
valueOf() is the function you're looking for.
Editing my answer (OP wants milliseconds of today, not since epoch)
You want the milliseconds() function OR you could go the route of moment().valueOf()
var timeArr = moment().format('x');
returns the Unix Millisecond Timestamp as per the format() documentation.
You could subtract the current time stamp from 12 AM of the same day.
Using current timestamp:
moment().valueOf() - moment().startOf('day').valueOf()
Using arbitrary day:
moment(someDate).valueOf() - moment(someDate).startOf('day').valueOf()
You can just get the individual time components and calculate the total. You seem to be expecting Moment to already have this feature neatly packaged up for you, but it doesn't. I doubt it's something that people have a need for very often.
Example:
var m = moment();
var ms = m.milliseconds() + 1000 * (m.seconds() + 60 * (m.minutes() + 60 * m.hours()));
console.log(ms);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Since this thread is the first one from Google I found, one accurate and lazy way I found is :
const momentObject = moment().toObject();
// date doesn't exist with duration, but day does so use it instead
// -1 because moment start from date 1, but a duration start from 0
const durationCompatibleObject = { ... momentObject, day: momentObject.date - 1 };
delete durationCompatibleObject.date;
const yourDuration = moment.duration(durationCompatibleObject);
// yourDuration.asMilliseconds()
now just add some prototypes (such as toDuration()) / .asMilliseconds() into moment and you can easily switch to milliseconds() or whatever !
I'm developing a website and using socket.io.I have items auctions and in my database I have set the time(unix timestamp) for each auction to end. When users bid on that item, if is there less than 20 seconds to end then the time on the database must change for it to get back to 20 seconds remaining. On every new bid the seconds left will be 20 seconds.
So with that said, that's what we have:
The client connects and gets the final time from server(server gets it from database and tells the client)
The client then must show the timeleft (currently showing xxx seconds) ( here's where I need help.)
When user bids, the server checks if the timer is under 20 seconds and if it is, the server adds UNIX_TIMESTAMP(NOW())+20 on database.
Long story short, what I need is the javascript to calculate the database stored timestamp minus the current unix timestamp (which it already does) and then turn it into 0:00...
Let's say database time - current time equals 600 seconds, how should I do to turn it into 5:00 output?
Thank You!
SOLUTION:
I'm sorry guys, this was really simple to solve and I found a solution after some advice. For those who are facing the same "problem" here is the solution I found and it couldn't be more simple
var time= 300;
var minutes = "0" + Math.floor(time / 60);
var seconds = "0" + (time - minutes * 60);
return minutes.substr(-2) + ":" + seconds.substr(-2);
Credits to the user who gave this answer on this thread: Javascript seconds to minutes and seconds
You would modulo the seconds by 60. Put the result in minutes and the remainder in seconds. Make sure you account for leading 0's. There might be some kind of string format for this but I don't know off the top of my head. Moment.js would make this very simple as well though, just take the current time, add the seconds, and use one of it's format options with m:ss.
There are a lot of examples on here to reference for moment.js. Here's an example: How to convert seconds to HH:mm:ss in moment.js
There is a simple fast and short solution to format seconds into M:SS (so without zero-padded minutes as your question asked for) :
function fmtMSS(s){return(s-(s%=60))/60+(9<s?':':':0')+s}
The function accepts either a Number (preferred) or a String (2 conversion 'penalties' which you can halve by prepending + in the function call's argument for s as in: fmtMSS(+strSeconds)), representing positive integer seconds s as argument.
Examples:
fmtMSS( 0 ); // 0:00
fmtMSS( '8'); // 0:08
fmtMSS( 9 ); // 0:09
fmtMSS( '10'); // 0:10
fmtMSS( 59 ); // 0:59
fmtMSS( +'60'); // 1:00
fmtMSS( 69 ); // 1:09
fmtMSS( 3599 ); // 59:59
fmtMSS('3600'); // 60:00
fmtMSS('3661'); // 61:01
fmtMSS( 7425 ); // 123:45
Breakdown:
function fmtMSS(s){ // accepts seconds as Number or String. Returns m:ss
return( s - // take value s and subtract (will try to convert String to Number)
( s %= 60 ) // the new value of s, now holding the remainder of s divided by 60
// (will also try to convert String to Number)
) / 60 + ( // and divide the resulting Number by 60 to give minutes
// (can never result in a fractional value = no need for rounding)
// to which we concatenate a String (converts the Number to String)
// who's reference is chosen by the conditional operator:
9 < s // if seconds is larger than 9
? ':' // then we don't need to prepend a zero
: ':0' // else we do need to prepend a zero
) + s ; // and we add Number s to the string (converting it to String as well)
}
Note: Negative range could be added by prepending (0>s?(s=-s,'-'):'')+ to the return expression (actually, (0>s?(s=-s,'-'):0)+ would work as well).
I am fairly new to HTML and Javascript, so I'm trying to make a small incremental game as practice. This is the code I am trying to use to calculate the automatic gains / second, as well as adjust accordingly for when the tab isn't in focus and setInterval stops running.
var startTime = new Date();
var endTime = new Date();
var interval = 100;
window.setInterval(function(){
startTime.getTime();
var timeDiff = startTime - endTime;
do{
document.getElementById('woodAmount').innerHTML = Math.floor(user.wood += (user.WPS/10));
document.getElementById('oilAmount').innerHTML = Math.floor(user.oil += (user.OPS/10));
document.getElementById('goldAmount').innerHTML = Math.floor(user.gold += (user.GPS/10));
document.getElementById('coalAmount').innerHTML = Math.floor(user.coal += (user.CPS/10));
timeDiff -= interval;
}while (timeDiff >= interval);
endTime.getTime();
}, interval);
For some reason, this code doesn't adjust for the time when the tab is not focused, but it works as expected when it is in focus.
As you can see here, I set the interval to 100 milliseconds, and I divide the resources / second (user.WPS) by 10.
However, when I set the interval to 1 second (1000 milliseconds) and don't divide the resources / second by 10, it works as expected all the time, and properly adjusts for the time that the tab isn't focused.
Can anyone offer an explanation as to why it works when using full-second intervals, but won't when using 100 millisecond intervals?
.getTime() gets the time that is already in the Date object at the time it was created or whenever the time was last set in the date object. It does NOT get the current time.
If you want to get the current time, I often use this little function:
function now() {
return new Date().getTime();
}
Or, if you don't need IE8 support, then you can use Date.now().
In addition, the getTime() method pulls the time out of the data object and returns it from that method call. If you want to use it, you have to put it somewhere after calling .getTime().
starttime=(new Date()).getTime();
endtime=(new Date()).getTime();
(endtime-starttime )/1000
will give a value.What is this value and why is it divided by 1000
Well, in this particular case the value will be 0.
you need to divide it by 1000 because time is represented in miliseconds, so to get the seconds you need to perform the transformation 1s = 1000ms
That code is calculating the number of seconds that have elapsed between two dates. The division by 1000 is there because the getTime() method returns a value measured in millseconds.
The code is actually needlessly long-winded. To get the milliseconds that have elapsed between two Date objects, you can just use the - operator on the Dates themselves:
var start = new Date();
// Some code that takes some time
var end = new Date();
var secondsElapsed = (end - start) / 1000;
value=millisecond delta, it is divided to turn the delta into seconds
Date getTime() gives the number of milliseconds since 1970 (Epoch)
Divide the difference by 1000 and you get seconds
Hii,
I have an input time in millisecounds. I want to include a digital stop watch in my application.i.e The time will dynamically change like a digital clock in every seconds.
You can divide the milliseconds by 1000 to get the seconds, then by 60 to get the minutes and by 60 again to get the hours. Or, even better, use modulo:
hours = parseInt(milliseconds / 3600) % 24;
minutes = parseInt(milliseconds / 60) % 60;
seconds = (milliseconds / 1000) % 60;
However if you want a time like 02:00 PM you must know from what time you started to count the milliseconds (ie, what time is it when the milliseconds are "0").
I'm not sure exactly what your question is, as in what specific parts you need help with. Even if you're not that familiar with Javascript, this is fairly simple to do "manually" by just dividing by each increasing factor and taking the remainder, e.g.:
var input = ...; // your input time
var millis = input % 1000;
input /= 1000;
var seconds = input % 60;
input /= 60;
var minutes = input % 60;
input /= 60;
var hours = input % 24; // I presume this will be less than 24 anyway)
var entireTime = hours + ':' + minutes + ':' + seconds;
An alternate way to do this would be to create a Date object passing the input time into the constructor; this would then represent that number of milliseconds past the epoch and so printing out its value would include the given time. Depending on what date formatting frameworks you have available this might be a more straightforward method - and it would certainly allow more flexibility in terms of manipulating the value.
Just a thought - make sure that you fully understand what the input actually is. It's relatively unusual to give an input time in milliseconds; I'd expect that such an input would actually be a duration. This admittedly could be the number of milliseconds past midnight, but do be sure that it's not the number of milliseconds past some other arbitrary starting point.
The prefix milli is 10^-3. Thus one millisecond is one thousandth of a second, 60 thousandth of a minute and 3600 thousandth of an hour. So 1,000 milliseconds is one second, 60,000 milliseconds is one minute and 3,600,000 milliseconds is one hour.
This means, devide the number of milliseconds by 1000 and you get the number of seconds, by 60,000 and you get the number of minutes, and by 3,600,000 and you get the number of hours.