Detect when the current date and time is now in Javascript - 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')
}

Related

Moment UTC time how to convert to seconds [duplicate]

I want a single number that represents the current date and time, like a Unix timestamp.
Timestamp in milliseconds
To get the number of milliseconds since Unix epoch, call Date.now:
Date.now()
Alternatively, use the unary operator + to call Date.prototype.valueOf:
+ new Date()
Alternatively, call valueOf directly:
new Date().valueOf()
To support IE8 and earlier (see compatibility table), create a shim for Date.now:
if (!Date.now) {
Date.now = function() { return new Date().getTime(); }
}
Alternatively, call getTime directly:
new Date().getTime()
Timestamp in seconds
To get the number of seconds since Unix epoch, i.e. Unix timestamp:
Math.floor(Date.now() / 1000)
Alternatively, using bitwise-or to floor is slightly faster, but also less readable and may break in the future (see explanations 1, 2):
Date.now() / 1000 | 0
Timestamp in milliseconds (higher resolution)
Use performance.now:
var isPerformanceSupported = (
window.performance &&
window.performance.now &&
window.performance.timing &&
window.performance.timing.navigationStart
);
var timeStampInMs = (
isPerformanceSupported ?
window.performance.now() +
window.performance.timing.navigationStart :
Date.now()
);
console.log(timeStampInMs, Date.now());
I like this, because it is small:
+new Date
I also like this, because it is just as short and is compatible with modern browsers, and over 500 people voted that it is better:
Date.now()
JavaScript works with the number of milliseconds since the epoch whereas most other languages work with the seconds. You could work with milliseconds but as soon as you pass a value to say PHP, the PHP native functions will probably fail. So to be sure I always use the seconds, not milliseconds.
This will give you a Unix timestamp (in seconds):
var unix = Math.round(+new Date()/1000);
This will give you the milliseconds since the epoch (not Unix timestamp):
var milliseconds = new Date().getTime();
I provide multiple solutions with descriptions in this answer. Feel free to ask questions if anything is unclear
Quick and dirty solution:
Date.now() /1000 |0
Warning: it might break in 2038 and return negative numbers if you do the |0 magic. Use Math.floor() instead by that time
Math.floor() solution:
Math.floor(Date.now() /1000);
Some nerdy alternative by Derek 朕會功夫 taken from the comments below this answer:
new Date/1e3|0
Polyfill to get Date.now() working:
To get it working in IE you could do this (Polyfill from MDN):
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
If you do not care about the year / day of week / daylight saving time you need to remember this for dates after 2038:
Bitwise operations will cause usage of 32 Bit Integers instead of 64 Bit Floating Point.
You will need to properly use it as:
Math.floor(Date.now() / 1000)
If you just want to know the relative time from the point of when the code was run through first you could use something like this:
const relativeTime = (() => {
const start = Date.now();
return () => Date.now() - start;
})();
In case you are using jQuery you could use $.now() as described in jQuery's Docs which makes the polyfill obsolete since $.now() internally does the same thing: (new Date).getTime()
If you are just happy about jQuery's version, consider upvoting this answer since I did not find it myself.
Now a tiny explaination of what |0 does:
By providing |, you tell the interpreter to do a binary OR operation.
Bit operations require absolute numbers which turns the decimal result from Date.now() / 1000 into an integer.
During that conversion, decimals are removed, resulting in a similar result to what using Math.floor() would output.
Be warned though: it will convert a 64 bit double to a 32 bit integer.
This will result in information loss when dealing with huge numbers.
Timestamps will break after 2038 due to 32 bit integer overflow unless Javascript moves to 64 Bit Integers in Strict Mode.
For further information about Date.now follow this link: Date.now() # MDN
var time = Date.now || function() {
return +new Date;
};
time();
var timestamp = Number(new Date()); // current time as number
In addition to the other options, if you want a dateformat ISO, you can get it directly
console.log(new Date().toISOString());
jQuery provides its own method to get the timestamp:
var timestamp = $.now();
(besides it just implements (new Date).getTime() expression)
REF: http://api.jquery.com/jQuery.now/
Date, a native object in JavaScript is the way we get all data about time.
Just be careful in JavaScript the timestamp depends on the client computer set, so it's not 100% accurate timestamp. To get the best result, you need to get the timestamp from the server-side.
Anyway, my preferred way is using vanilla. This is a common way of doing it in JavaScript:
Date.now(); //return 1495255666921
In MDN it's mentioned as below:
The Date.now() method returns the number of milliseconds elapsed since
1 January 1970 00:00:00 UTC.
Because now() is a static method of Date, you always use it as Date.now().
If you using a version below ES5, Date.now(); not works and you need to use:
new Date().getTime();
console.log(new Date().valueOf()); // returns the number of milliseconds since the epoch
Performance
Today - 2020.04.23 I perform tests for chosen solutions. I tested on MacOs High Sierra 10.13.6 on Chrome 81.0, Safari 13.1, Firefox 75.0
Conclusions
Solution Date.now() (E) is fastest on Chrome and Safari and second fast on Firefox and this is probably best choice for fast cross-browser solution
Solution performance.now() (G), what is surprising, is more than 100x faster than other solutions on Firefox but slowest on Chrome
Solutions C,D,F are quite slow on all browsers
Details
Results for chrome
You can perform test on your machine HERE
Code used in tests is presented in below snippet
function A() {
return new Date().getTime();
}
function B() {
return new Date().valueOf();
}
function C() {
return +new Date();
}
function D() {
return new Date()*1;
}
function E() {
return Date.now();
}
function F() {
return Number(new Date());
}
function G() {
// this solution returns time counted from loading the page.
// (and on Chrome it gives better precission)
return performance.now();
}
// TEST
log = (n,f) => console.log(`${n} : ${f()}`);
log('A',A);
log('B',B);
log('C',C);
log('D',D);
log('E',E);
log('F',F);
log('G',G);
This snippet only presents code used in external benchmark
Just to add up, here's a function to return a timestamp string in Javascript.
Example: 15:06:38 PM
function displayTime() {
var str = "";
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
if (minutes < 10) {
minutes = "0" + minutes
}
if (seconds < 10) {
seconds = "0" + seconds
}
str += hours + ":" + minutes + ":" + seconds + " ";
if(hours > 11){
str += "PM"
} else {
str += "AM"
}
return str;
}
One I haven't seen yet
Math.floor(Date.now() / 1000); // current time in seconds
Another one I haven't seen yet is
var _ = require('lodash'); // from here https://lodash.com/docs#now
_.now();
The Date.getTime() method can be used with a little tweak:
The value returned by the getTime method is the number of milliseconds
since 1 January 1970 00:00:00 UTC.
Divide the result by 1000 to get the Unix timestamp, floor if necessary:
(new Date).getTime() / 1000
The Date.valueOf() method is functionally equivalent to Date.getTime(), which makes it possible to use arithmetic operators on date object to achieve identical results. In my opinion, this approach affects readability.
The code Math.floor(new Date().getTime() / 1000) can be shortened to new Date / 1E3 | 0.
Consider to skip direct getTime() invocation and use | 0 as a replacement for Math.floor() function.
It's also good to remember 1E3 is a shorter equivalent for 1000 (uppercase E is preferred than lowercase to indicate 1E3 as a constant).
As a result you get the following:
var ts = new Date / 1E3 | 0;
console.log(ts);
I highly recommend using moment.js. To get the number of milliseconds since UNIX epoch, do
moment().valueOf()
To get the number of seconds since UNIX epoch, do
moment().unix()
You can also convert times like so:
moment('2015-07-12 14:59:23', 'YYYY-MM-DD HH:mm:ss').valueOf()
I do that all the time. No pun intended.
To use moment.js in the browser:
<script src="moment.js"></script>
<script>
moment().valueOf();
</script>
For more details, including other ways of installing and using MomentJS, see their docs
For a timestamp with microsecond resolution, there's performance.now:
function time() {
return performance.now() + performance.timing.navigationStart;
}
This could for example yield 1436140826653.139, while Date.now only gives 1436140826653.
Here is a simple function to generate timestamp in the format: mm/dd/yy hh:mi:ss
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' +
(now.getDate()) + '/' +
now.getFullYear() + " " +
now.getHours() + ':' +
((now.getMinutes() < 10)
? ("0" + now.getMinutes())
: (now.getMinutes())) + ':' +
((now.getSeconds() < 10)
? ("0" + now.getSeconds())
: (now.getSeconds())));
}
You can only use
var timestamp = new Date().getTime();
console.log(timestamp);
to get the current timestamp. No need to do anything extra.
// The Current Unix Timestamp
// 1443534720 seconds since Jan 01 1970. (UTC)
// seconds
console.log(Math.floor(new Date().valueOf() / 1000)); // 1443534720
console.log(Math.floor(Date.now() / 1000)); // 1443534720
console.log(Math.floor(new Date().getTime() / 1000)); // 1443534720
// milliseconds
console.log(Math.floor(new Date().valueOf())); // 1443534720087
console.log(Math.floor(Date.now())); // 1443534720087
console.log(Math.floor(new Date().getTime())); // 1443534720087
// jQuery
// seconds
console.log(Math.floor($.now() / 1000)); // 1443534720
// milliseconds
console.log($.now()); // 1443534720087
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If it is for logging purposes, you can use ISOString
new Date().toISOString()
"2019-05-18T20:02:36.694Z"
Any browsers not supported Date.now, you can use this for get current date time:
currentTime = Date.now() || +new Date()
This seems to work.
console.log(clock.now);
// returns 1444356078076
console.log(clock.format(clock.now));
//returns 10/8/2015 21:02:16
console.log(clock.format(clock.now + clock.add(10, 'minutes')));
//returns 10/8/2015 21:08:18
var clock = {
now:Date.now(),
add:function (qty, units) {
switch(units.toLowerCase()) {
case 'weeks' : val = qty * 1000 * 60 * 60 * 24 * 7; break;
case 'days' : val = qty * 1000 * 60 * 60 * 24; break;
case 'hours' : val = qty * 1000 * 60 * 60; break;
case 'minutes' : val = qty * 1000 * 60; break;
case 'seconds' : val = qty * 1000; break;
default : val = undefined; break;
}
return val;
},
format:function (timestamp){
var date = new Date(timestamp);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
// Will display time in xx/xx/xxxx 00:00:00 format
return formattedTime = month + '/' +
day + '/' +
year + ' ' +
hours + ':' +
minutes.substr(-2) +
':' + seconds.substr(-2);
}
};
This one has a solution : which converts unixtime stamp to tim in js try this
var a = new Date(UNIX_timestamp*1000);
var hour = a.getUTCHours();
var min = a.getUTCMinutes();
var sec = a.getUTCSeconds();
I learned a really cool way of converting a given Date object to a Unix timestamp from the source code of JQuery Cookie the other day.
Here's an example:
var date = new Date();
var timestamp = +date;
If want a basic way to generate a timestamp in Node.js this works well.
var time = process.hrtime();
var timestamp = Math.round( time[ 0 ] * 1e3 + time[ 1 ] / 1e6 );
Our team is using this to bust cache in a localhost environment. The output is /dist/css/global.css?v=245521377 where 245521377 is the timestamp generated by hrtime().
Hopefully this helps, the methods above can work as well but I found this to be the simplest approach for our needs in Node.js.
For lodash and underscore users, use _.now.
var timestamp = _.now(); // in milliseconds
Moment.js can abstract away a lot of the pain in dealing with Javascript Dates.
See: http://momentjs.com/docs/#/displaying/unix-timestamp/
moment().unix();
As of writing this, the top answer is 9 years old, and a lot has changed since then - not least, we have near universal support for a non-hacky solution:
Date.now()
If you want to be absolutely certain that this won't break in some ancient (pre ie9) browser, you can put it behind a check, like so:
const currentTimestamp = (!Date.now ? +new Date() : Date.now());
This will return the milliseconds since epoch time, of course, not seconds.
MDN Documentation on Date.now
more simpler way:
var timeStamp=event.timestamp || new Date().getTime();

How to check if open to close time has elapse using timezone in javascript

I have this below functionin my webapp to check if from OPEN to CLOSE time has elapse using a country timezone and it's working fine. Am trying to optimize my website, so my question is how can i make a function like this in javascript without the use of moment timezone? The moment timezone file is large and this is the only usage of it on my website.
function isOpen(openTime, closeTime, timezone) {
// handle special case
if (openTime === "24HR") {
return "open";
}
// get the current date and time in the given time zone
const now = moment.tz(timezone);
// Get the exact open and close times on that date in the given time zone
const date = now.format("YYYY-MM-DD");
const storeOpenTime = moment.tz(date + ' ' + openTime, "YYYY-MM-DD h:mmA", timezone);
const storeCloseTime = moment.tz(date + ' ' + closeTime, "YYYY-MM-DD h:mmA", timezone);
let check;
if (storeCloseTime.isBefore(storeOpenTime)) {
// Handle ranges that span over midnight
check = now.isAfter(storeOpenTime) || now.isBefore(storeCloseTime);
} else {
// Normal range check using an inclusive start time and exclusive end time
check = now.isBetween(storeOpenTime, storeCloseTime, null, '[)');
}
return check ? "open" : "closed";
}
const zone = "Asia/Kuala_Lumpur";
console.log("24HR", isOpen("24HR", undefined, zone));
console.log("2:00AM-8:00AM", isOpen("2:00AM", "8:00AM", zone));
console.log("8:00AM-10:00AM", isOpen("8:00AM", "10:00PM", zone));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.27/moment-timezone-with-data-10-year-range.min.js"></script>
You can use the Intl.DateTimeFormat constructor to do the same thing. As I understand it, you want to know if a store that is open say from 8:00 to 12:00 in say Asia/Kuala_Lumpur is currently open.
It's probably possible to convert your code more or less line by line, but I've just refactored it and simplified the logic (call me lazy…). This way it gets the current time in the desired location, converts it to minutes since midnight, then sees if that is before the start time or on or after the closing time.
For midnight (12:00 AM), the time converts to 0 minutes so if closingTime is 0, it's assumed to be end of day so is set to 1,440 (i.e. midnight at end of day).
The test times only work on the same day, if the open time runs over midnight you'll need to refactor it. I've just tested midnight to noon and noon to midnight so one should always show "open" and the other "closed".
You might also consider using Luxon, it does what moment.js + moment.tz does but uses the Intl object instead of included data.
Edit
To deal with times that go over midnight, you can either include dates in the time (not convenient if you want to use a regular daily schedule) or you can have an "inside" and "outside" test so that if closing time is before the open time, you test if the time is not between open and close times. That can be done by comparing openMin and close times and adjusting the test.
This will not deal with overlapping start and end times, but that doesn't really fit a regular daily schedule (though it might fit a weekly or longer schedule).
/* #param {string} location: IANA representative location
** #param {Date} date: date instance to get time from, default is now
** #returns {string} time in location in h:mm ap format
*/
function getTime(location, date = new Date()) {
return date.toLocaleString('en', {
timeZone: location,
hour : 'numeric',
minute: '2-digit',
dayPeriod: 'short'
});
}
/* #param {string} time: h:mm A
** #returns {number} time converted to minutes
*/
function timeToMin(time) {
let [h, m] = time.match(/\d\d?/g);
h = h%12;
if (/pm$/i.test(time)) h +=12
return h * 60 + parseInt(m);
}
/* #param {string} openTime: opening time in h:mm ap format
** #param {string} closeTime: closing time in h:mm ap format
** #param {string} location: IANA representative location
** #return {string} open if current time is within openTime and closeTime in location,
** closed otherwise
*/
function isOpen(openTime, closeTime, location) {
if (openTime == '24HR') return 'open';
let nowTime = getTime(location);
let nowMin = timeToMin(nowTime);
let openMin = timeToMin(openTime);
let closeMin = timeToMin(closeTime) || 1440;
// Open and close on same day
if (openMin < closeMin) {
return nowMin < openMin || nowMin >= closeMin ? 'closed' : 'open';
// Close on day after open
} else {
return nowMin >= openMin && nowMin < closeMin ? 'open' : 'closed';
}
}
// Time in KL
let loc = "Asia/Kuala_Lumpur";
console.log(`In ${loc} it's ${getTime(loc)}`);
// Examples
[["24HR", undefined, loc], // Open 24 hrs
["12:00AM", "12:00PM", loc], // Midnight to noon
["12:00PM", "12:00AM", loc], // Noon to midnight
["6:30PM", "04:00AM", loc], // Over midnight
].forEach(args => console.log(
`${args[0]}${args[1]? '-' + args[1] : ''} ${isOpen(...args)}`
));

Convert Text to Integer in JS

I am trying to use Tampermonkey to find a UTC time offset and return it as as a time. The website shows an offset which I pull here
waitForKeyElements (".UTCText", getTZ_Offset);
which returns a string
console.log ("Found timezone offset: ", tzOffset);
usually like this 08:00 It can be + or -
Then i want to convert that into actual time. Eg if UTC time is 00:00, I would like to print a string "The users time is 08:00" if the offset was +08:00.
I thought i could use momentjs to get UTC time moment().utcOffset(tzOffset) and pass the offset.
When i do that it just returns NaN
What am I doing wrong?
Multiply the part before the : by 60, and add it to the second part:
const tzOffset = '08:00';
const [hourOffset, minuteOffset] = tzOffset.split(':').map(Number);
const totalMinuteOffset = hourOffset * 60 + minuteOffset;
console.log(totalMinuteOffset);
If the input may be negative, then check that as well:
const tzOffset = '-08:00';
const [_, neg, hourOffset, minuteOffset] = tzOffset.match(/(-)?(\d{2}):(\d{2})/);
const totalMinuteOffset = (neg ? -1 : 1) * (hourOffset * 60 + Number(minuteOffset));
console.log(totalMinuteOffset);
A few time zones differ from UTC not only by hours, but by minutes as well (eg, UTC +5:30, UTC +9:30), so just parseInt, even if it worked, wouldn't be reliable everywhere.

Javascript time difference

I am trying to simply calculate the time difference of 5:30:00 - 2:30:00. Obviously this should result in 3:00:00
However when I execute following code in console
var a = new Date(0,0,0,5,30,0)
var b = new Date(0,0,0,2,30,0)
var c = new Date(a-b)
console.log(c.getHours() + ":" + c.getMinutes() + ":" + c.getSeconds())
The result is 4:00:00.
What is causing this problem? And how should I handle it?
Date constructor is not suitable to either represent or deal the time spans.
There are no built-in tools to handle time spans in JS, so you need to implement one yourself.
Thankfully the time string -> seconds conversion is trivial:
const timeToSec = time => time.split(':').reduce((acc, v) => acc * 60 + parseInt(v), 0);
Then you can deal with seconds:
const diffInSeconds = timeToSec('5:30:00') - timeToSec('2:30:00'); // 10800
The reverse transformation of seconds -> time string is also trivial (and tbh it's simple reversed of the timeToSec implementation) and I'm leaving it as a home work.
The reason why people get different results is timezone.
When you calculate c as the difference between two dates, you actually get a date relative to 01.01.1970. In this case, when you do:
console.log(c);
You get something like:
1970-01-01T03:00:00.000Z
This is in UTC Date format.
But now if you would display c in the local time zone:
console.log(c.toLocaleDateString()+ ' ' + c.toLocaleTimeString());
... then you get maybe this:
1-1-1970 04:00:00
If you then take the hours of that date with getHours(), you get them from the date/time as it is in your time zone, in your case you are on GMT+1, which means the outcome is 4.
To avoid this time zone conversion, use the UTC versions of the getXXXX functions, like getUTCHours. Note that some time zones have non-integer hour differences with UTC (with an half-hour part), so they would need to use getUTCMinutes as well.
Be aware that converting date differences to Date format will start to give wrong results when you cover larger spans, crossing 29 February, ...etc. Differences are best calculated by taking the date differences (in milliseconds) without conversion to Date. From there it is straightforward to calculate the number of seconds, minutes, ...etc.
I would like to assume that your question is not merely about the difference between two numbers, but it is a real problem.
Then, the answer is: without specifying the day(s), the difference between two hours is meaningless, you must always specify which day(s) you are talking about.
For example Europe, Berlin:
Sunday, 27 March 2016, 02:00:00 clocks were turned
forward 1 hour.
Like in your example, this would lead to pay someone 1 hour more than it had worked...
Sunday, 30 October 2016, 03:00:00 clocks are turned backward 1 hour
..calculating the same interval Sunday, 30 October 2016 would do the opposite.
Moreover, be aware that daylight saving time has become standard in the U.S., Canada, and most European countries. However, most of the world doesn't even use it.
Moreover, during the past, starting day and ending day of saving time has been changed from year to year, and the starting hour has been also changed, i.e. you cannot assume always 2.00 at night - so reconstruct an interval without knowing this information would not lead to a correct result.
A possible solution to calculate correctly a duration, is always to store next the Local Date/Time also the UTC Date/Time and do the calculation keeping both in account, so you have both the Timezone and the Daylight Saving Time Shift to get back the exact start date/time and ending date/time.
If you don't have this information already stored, then you should retrieve them, for example, from a online Time Database.
usage
node time_diff.js 5:30:00 2:30:00
will output: 03:00:00
code of time_diff.js:
#!/usr/bin/env node
if (!process.argv[2] || !process.argv[3]) {
console.log('usage: time_diff hh:mm:ss hh:mm:ss');
process.exit(1);
}
const timeToSec = (time) => time.split(':').reduce((acc, v) => acc * 60 + parseInt(v), 0);
const diffInSeconds = (time1, time2) => timeToSec(time2) - timeToSec(time1);
const hhmmss = (secs) => {
var minutes = Math.floor(secs / 60);
secs = secs % 60;
var hours = Math.floor(minutes / 60);
minutes = minutes % 60;
return pad(hours) + ":" + pad(minutes) + ":" + pad(secs);
function pad(num) {
return ("0" + num).slice(-2);
}
};
try {
console.log(hhmmss(diffInSeconds(process.argv[3], process.argv[2])));
}
catch (err) {
console.log('usage: time_diff hh:mm:ss hh:mm:ss');
process.exit(1);
}
Try this simple plugin to get time differences.
https://github.com/gayanSandamal/good-time
import the goodTimeDiff method from good-time.js to your project
import {goodTimeDiff} from './scripts/good-time.js'
declare an object to give settings like below. let settings = {}
now assign time values to the declared object variable. *time must be in standard format and must be a string! *'from' is optional the default value will be the browser current time.
let settings = {
'from': '2019-01-13T00:00:29.251Z',
'to': '2018-09-22T17:15:29.251Z'
}
now calllback the method called goodTimeDiff() and pass the settings object variable as a parameter.
goodTimeDiff(settings)
Finally assign the method to any variable you want.
let lastCommentedTime = goodTimeDiff(timeSettings)
a - b results in three hours, but in milliseconds. You just need to convert milliseconds to hours (which is not new Date(milliseconds)).
try: (a-b)/1000/60/60
Formatted:
var a = new Date(0,0,0,5,30,0)
var b = new Date(0,0,0,2,30,0)
var diff = (a.getTime()-b.getTime())
var h = Math.floor(diff/1000/60/60)
var m = ('0' + Math.floor((diff/1000/60)%60) ).substr(-2)
var s = ('0' + Math.floor((diff/1000)%60) ).substr(-2)
console.log(h + ':' + m + ':' + s)
EDIT
For those who want to treat a time span as a date... just get the UTC date, which means Coordinated Universal Time. In other words, don't use timezone aware methods:
var a = new Date(0,0,0,5,30,0)
var b = new Date(0,0,0,2,30,0)
var c = new Date(a-b)
console.log(c.getUTCHours() + ":" + c.getUTCMinutes() + ":" + c.getUTCSeconds())
Be aware though, this will fall apart on edge cases...

Get a difference between random seconds and now-then in 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).

Categories