Get a difference between random seconds and now-then in Javascript - javascript

I've got a little bit of javascript that generates a random number that will count as milliseconds(Between 0 and 10 seconds).
Along with it i'm using the getTime() method to set a starttimer and a while later again to set a stoptimer.
With that i want to get the difference in milliseconds between the timedifference(stoptimer-starttimer) and the milliseconds i choose at random.
Something like: The random milliseconds is 1.3s and the timedifference is 1. The user is off by 0.3s.
millisecondsToPress = Math.floor((Math.random()*100)+1)*1000;
startTime = attempt.getCurrentTime();
And a little later a showresult is called which stops the time and should do the math
stopTime = attempt.getCurrentTime();
showResult();
And here's the getTime function:
var d = new Date();
return d.getTime();
And the showresult as it is now(Which is wrong :-p)
var secondsPressed = this.stopTime - this.startTime;
if (secondsPressed >= this.millisecondsToPress) {
//The timedifference is bigger than the toPress. The player overshot!
result = secondsPressed - this.millisecondsToPress;
} else {
//The player undershot
result = this.millisecondsToPress - secondsPressed;
}
I'm propably wrong with the milliseconds or something(*1000 or *100 etc)

Your random time generator is giving you values between 1 and 100 seconds, and only in whole seconds because the * 1000 happens after the random time has been rounded. You probably want:
var millisecondsToPress = Math.floor(10000 * Math.random());
If you only care about the magnitude of the error, use Math.abs()
result = Math.abs(secondsPressed - this.millisecondsToPress) / 1000.0
with the division there to convert back to seconds.
To get the numeric value of the current time in milliseconds, you can just use +new Date()
on older browsers, or Date.now() on newer browsers (the latter is more efficient because it doesn't instantiate an object).

Related

Detect when the current date and time is now in Javascript

Im trying to find if the current time and date is equal to a date coming from an API.
The api data is in the following format: 2021-01-02T08:00:00+01:00
The code i currently have is:
if (new Date() === new Date(apiData) {
alert('its the current time accurate to seconds')
}
The problem is that i don't think that this takes in account different timezones, I only want to run the code if the time is exactly as the one from api, no matter where the client is coming from.
The timestamp 2021-01-02T08:00:00+01:00 represents a unique moment in time. If parsed according to ECMA-262, it will produce a time value that is a millisecond offset from the ECMAScript epoch: 1970-01-01T00:00:00Z.
The generated time value is independent of host system settings, i.e. the host offset has no effect. So:
Date.parse('2021-01-02T08:00:00+01:00');
will produce exactly the same value (1609570800000) in every implementation consistent with ECMA-262.
If passed to the Date constructor, the timestamp will be parsed in exactly the same way, with the time value being used for a Date instance such that:
let ts = '2021-01-02T08:00:00+01:00';
Date.parse(ts) == new Date(ts).getTime();
As mentioned in comments, ECMAScript time values have millisecond precision, so the chance that the above will return true is extremely small. Reducing precision to one second (say by rounding or truncating the decimal seconds) won't help much.
If you want to run some code at the time indicated by the timestamp, you are best to work out the time left and, if it's in the future, set a timeout, something like:
let timeLeft = Date.parse(timestamp) - Date.now();
if (timeLeft >= 0) {
setTimeout(doStuff, timeLeft);
}
E.g.
/* Create timestamp in future with specified offset
* #param {string} timeAhead - time in future in H[:m[:s[.sss]]] format
* #param {string} offset - offset as [-]H[:mm]
* #returns {string} ISO 8601 formatted timestamp with offset
*/
function getFutureTimestamp(timeAhead, offset) {
let pad = n => ('0' + n).slice(-2);
let [h, m, s, ms] = timeAhead.split(/\D/);
let timems = (h||0)*3.6e6 + (m||0)*6e4 + (s||0)*1e3 + (ms||0)*1;
let oSign = /^-/.test(offset)? -1 : +1;
let [oH, om] = offset.match(/\d+/g) || [];
let oms = oSign * (oH*3.6e6 + (om||0)*6e4);
let d = new Date(Date.now() + oms + timems);
return d.toISOString().replace('Z', `${oSign < 0? '-':'+'}${pad(oH)}:${pad(om||0)}`);
}
// timestamp for 5 seconds from now with offset +1
let ts = getFutureTimestamp('0:0:5','1');
// Calculate ms from now to ts
let delay = Date.parse(ts) - Date.now();
console.log('Run at ' + ts);
// Show timestamp after lag
if (delay >= 0) {
setTimeout(()=>console.log('done: ' + new Date().toISOString()), delay);
}
Note that in the above, the first displayed timestamp will be +1, the second +0 so they will be 1 hour different.
Timeouts don't necessarily run after exactly the time specified. However, the above seems to be a few milliseconds. As far as I know, the accuracy of the timeout (based on the system clock) isn't dependent on the length of the delay but on how busy the system is when it's elapsed.
Use This Code
if (new Date().getTime() === new Date(apiData).getTime()) {
alert('its the current time accurate to seconds')
}

How to calculate difference between saved timestamp and current time

I saved a timestamp in this format .
So what I want to do now is calculate the difference between the current time and the saved timestamap in a JavaScript function. But I have no idea how to do that.
Hope anyone can help.
When you fetch the document, 'timestamp' field would be of type Timestamp and you can use seconds property and current timestamp to calculate the difference as shown below:
const snap = await getDoc(docRef);
const timeDiff = Date.now() - snap.data()?.time.seconds * 1000;
console.log(`Time Difference: ${timeDiff} ms`)
This is actually very easy to achieve. Most important to know is that the function Date.now() returns you the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.
To get the duration between to timestamps is like "end - begin = duration".
Here is a code example:
// collect the first timestamp
const beginTimestamp = Date.now()
// here comes a for loop to consume some time, otherwise you will get 0 milliseconds
for (var i=0; i<10000; i++) {
"Some kind of string".split("").reverse().join("")
}
// collect the second timestamp
const endTimestamp = Date.now()
// subtract the first from the second timestamp tells you the milliseconds in between of both timestamps
console.log("Duration in milliseconds:", endTimestamp - beginTimestamp)

Date.getSeconds() isn't returning what I'm expecting

I have the following code:
let startDate = new Date(someDateCreated);
let timerDate = new Date(null);
timerDate.setSeconds((currentTime - startDate) / 1000);
console.log(timerDate.getSeconds());
Assuming currentTime is always now and someDateCreated starts at 2 minutes ago, I'd expect to log 120 but it is logging 1. And if I setInterval a function that does this every second it just counts 1, 2, 3... Doing the following
console.log((currentTime - startDate) / 1000);
does what I'd expect. Why does Date.getSeconds() not give me the seconds I set on it?
Here's a pen.
So tracking this down a bit, while I can setSeconds() with values greater than 59 and have the date update the minutes/hours/etc correctly, getSeconds() would always seem to return the seconds between 0-59 of whatever the date object is.
timerDate.getTime() / 1000 is actually what I need.

Convert any String time to seconds

I'm trying to convert 15:00 (15minutes) to seconds though I get 54,000 when I use this below.
I'm trying to convert 15minutes to seconds.
S = '15:00';
D = "1/1/1 "
s = ( new Date(D+S) - new Date(D) )/1000
alert(s);
Though when I do the math, it's 60 x 15 = 900. How do I get 900, since the time is a random string.
Well if your format will always be "mm:ss" you could dome string parsing and do the math manually, of course this would need to be adjusted depending on the input format.
S = '15:25';
var times = S.split(":");
var minutes = times[0];
var seconds = times[1];
seconds = parseInt(seconds, 10) + (parseInt(minutes, 10) * 60);
alert(seconds);​
Note in the example I explicitly added 25 seconds just as demonstration.
http://jsfiddle.net/Jg4gB/
The time string '15:00' in JavaScript refers to the time of day 1500hr, or 3:00 p.m. American-style. That's 15 hours after midnight. That explains why you got 54,000 seconds.
If you wanted to express 15 minutes using your method of manipulating date strings, try '00:15:00'.

Countdown timer with cookies

I know there have been a lot of topics like this but I just have problem to which I couldn't find the answer.
My script is:
window.onload = function(){
// 200 seconds countdown
var countdown = 14400;
//current timestamp
var now = Date.parse(new Date());
//ready should be stored in your cookie
if ( !document.cookie )
{
document.cookie = Date.parse(new Date (now + countdown * 1000)); // * 1000 to get ms
}
//every 1000 ms
setInterval(function()
{
var diff = ( document.cookie - Date.parse(new Date()) );
if ( diff > 0 )
{
var message = diff/1000 + " seconds left";
}
else
{
var message = "finished";
}
document.body.innerHTML = message;
},1000);
}
I want to make countdown timer which tells user time how much left depending on his cookie value. So far I managed to calculate difference between two values but I don't know how to make format like, let's say, "dd/mm/yy hh:mm:ss" from difference timestamp (diff). Is it possible at all?
What you want is a function that converts difference in (mili)seconds to something like
5d 4h 3m 2s
If you don't mind having a large number of days for times periods > a few months, then you could use something like this:
function human_time_difference(diff) {
var s = diff % 60; diff = Math.floor(diff / 60);
var min = diff % 60; diff = Math.floor(diff / 60);
var hr = diff % 24; diff = Math.floor(diff / 24);
var days = diff;
return days + 'd ' + hr + 'h ' + min + 'm ' + s + 's';
}
If you have the difference in miliseconds, you'll need to pass the that number divided by 1000. You can also use Math.round to get rid of fractions, but you could just as well leave them on if you want that information displayed.
Getting months and years is a little trickier for a couple of reasons:
The number of days in a month varies.
When you're going from the middle of one month to the middle of the next, the time span doesn't cover any whole months, even if the number of days > 31 (e.g. How many months are there between the 2nd of June and the 30th of July??).
If you really want the number of months between two times, the number of seconds between them is not enough. You have to use calendar logic, which requires passing in the start and end date + time.
PS: When you post a question, avoid irrelevant details. For example, your question has nothing to do with cookies, setInterval, or onload handlers. The only part that you don't know is how to convert (mili)seconds to days, hours, etc. It might be helpful to supply some background on why you're trying to do something, but if it's not essential to understand the basic question, put it at the end so that people don't have to wade through it before getting to the essential part. The same advice applies to your title; make sure it's relevant by excluding irrelevant details (e.g. cookies and counting down).
JavaScript doesn't have any built in date formatting methods like you might expect if you've done any PHP. Instead, you have to build the string manually. However, there are a number of getter methods that will be useful to this end. See 10 ways to format time and date using JavaScript.
Also, just so you know. Date.parse doesn't return the millisecond portion of the time stamp (it rounds down). If you need the milliseconds, you can do either of the following
var d = new Date();
var timestamp_ms = Date.parse(d) + d.getMilliseconds();
or just
var timestamp_ms = +d;
I do not understand why you check the cookie by if ( !document.cookie ) But it doesnot work on my browser so I modified it into if ( document.cookie )
Try toString function and other. Look them up in javascript Date object reference. For example,
var t = new Date;
t.setTime(diff);
var message = t.toTimeString() + " seconds left";
This will print 11:59:58 seconds left on my browser.

Categories