Check if the time difference is less than 1 second in moment - javascript

In my javascript project, I want to check if the time difference is less than 1 second. I use moment to get this difference. This is the function I have written to achieve it.
const withinOneSecond = (time) => {
const currentTime = moment();
return time + 1000 < currentTime;
};
But this doesn't work as expected. How can I check if the given time is within a second to the current time?

You can use moment#diff.
As an example, I've added a second to a date and taking the difference in with .diff passing seconds as second argument should return the difference in seconds
var a = moment();
var b = moment().add(1, 'seconds');
console.log(b.diff(a, 'seconds'))
<script src="https://momentjs.com/downloads/moment.js"></script>
The supported measurements are years, months, weeks, days, hours, minutes, and seconds. Here
For your particular case, you should be doing something like
const withinOneSecond = (time) => {
const currentTime = moment();
return currentTime.diff(time, 'seconds') == 1
};
var time = moment().add(1, 'seconds');
let results = withinOneSecond(time);
console.log(results);
<script src="https://momentjs.com/downloads/moment.js"></script>

You dont need moment for this. Use vanilla, use .getTime() to get time in milliseconds and compare it with the current time. See the code below:
var date = new Date();
const withinOneSecond = (time) => new Date().getTime() - new Date(time).getTime() < 1000;
setTimeout(() => {
console.log(withinOneSecond(date)); // true
}, 500)
setTimeout(() => {
console.log(withinOneSecond(date)); // false
}, 1500)

You just need to use the duration.asHours() method (see the docs).
const withinOneSecond = (time) => {
const currentTime = moment();
return moment.duration(currentTime.diff(time)).asSeconds() > 1;
};

Related

How can i make a script load faster?

Im making a digital clock for my webpage. But every time i enter the page, it takes 1 second before the string with the current time appears. Is there any way to change that and make it faster so it is not that notisable for the user? Thank you
My js code:
const add_zero = (number) => {
return number < 10 ? `0${number}` : number;
}
const show_current_time = () => {
setInterval(() => {
const today = new Date();
const month = today.getMonth() + 1;
const year = today.getFullYear();
const date = today.getDate();
const hours = add_zero(today.getHours());
const minutes = add_zero(today.getMinutes());
const current_date = `${date}/${month}/${year} ${hours}:${minutes} |`;
document.getElementById("show_current_time").innerHTML = current_date;
}, 1000)
}
window.onload = show_current_time;
You can try calling a function that does the work once, and only then do the setInterval() for that function.
set_current_time()
setInterval(set_current_time, 1000);
It "takes 1 second before the string with the current time appears", because the function show_current_time has setInterval and the last argument is 1000 (1 second).
The function is doing more than what its name suggests: showing the current time. It's also updating it each second. It starts the first update after the document is loaded.
Remove setInterval:
const show_current_time = () => {
const today = new Date();
const month = today.getMonth() + 1;
const year = today.getFullYear();
const date = today.getDate();
const hours = add_zero(today.getHours());
const minutes = add_zero(today.getMinutes());
const current_date = `${date}/${month}/${year} ${hours}:${minutes} |`;
document.getElementById("show_current_time").innerHTML = current_date;
}
If you add show_current_time();, it will call the function sooner.
Calling setInterval(show_current_time, 1000); updates it each second.
window.addEventListener(
'load',
() => {
show_current_time();
setInterval(show_current_time, 1000);
}
);
I avoid using window.load because you lose everything you did with it when you change it.
There might be a gap between the beginning of the document being loaded, and the functions being called. But, depending on the script size how, and how it's loaded, probably it's not noticeable.
use requestAnimation frame, on a recursive loop:
https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
const show_current_time = () => {
const today = new Date();
const month = today.getMonth() + 1;
const year = today.getFullYear();
const date = today.getDate();
const hours = add_zero(today.getHours());
const minutes = add_zero(today.getMinutes());
const current_date = `${date}/${month}/${year} ${hours}:${minutes} |`;
document.getElementById("show_current_time").innerHTML = current_date;
}
show_current_time()
setInterval(show_current_time,1000)

Why does setInterval return the same value when using the Date method

I am trying to get the local seconds from the getSeconds but when I console.log the results by adding the function in setInterval the seconds are the same yet they are increasing. please find my code below;
const time = new Date();
function clock() {
const seconds = time.getSeconds();
console.log(seconds)
}
let interval = setInterval('clock()', 1000);
You are assigning the value for time outside (and only once) of your interval-func, therefore it's always the same. Try:
function clock() {
let time = new Date();
const seconds = time.getSeconds();
console.log(seconds)
}
let interval = setInterval('clock()', 1000);
you create one data object (in some moment) and then you call getSeconds on the same data object so you have the same result
function clock() {
const seconds = new Date().getSeconds();
console.log(seconds)
}
let interval = setInterval(clock, 1000);

Calculate difference between dates and start counting from that difference

I'm new to angular, I would like to know if there is there a way to calculate the difference between a specific date and the current date, and then start counting the time from that difference?
Example: 29/01/2020 21:00:00 - 29/01/2020 21:30:00 gives a difference of 30 minutes ... the count should start from 30 minutes, that is 00:30:00
Demo
Code
startTime(){
this.interval = setInterval(() => {
if (this.time === 0) {
this.time++;
} else {
this.time++;
}
this.display = this.time;
return this.display;
}, 1000);
}
You could compute a difference between the two dates in milliseconds using Date.getTime(). If you create a new Date object from this difference, it will contain a representation of this interval. So you only need to increment the seconds and display the formatted time:
// difference between two dates in milliseconds
const diff = new Date('May 1,2019 11:20:00').getTime() - new Date('May 1,2019 11:00:00').getTime();
// new date object created from this difference
const start = new Date(diff);
const el = document.getElementById('time');
setInterval(() => {
// updating the time every second
start.setSeconds(start.getSeconds() + 1);
el.innerHTML = `${format(start.getUTCHours())}: ${format(start.getUTCMinutes())}: ${format(start.getUTCSeconds())}`;
}, 1000)
function format(n) {
return n < 10 ? '0' + n : '' + n;
}
<div id=time></div>
I would recommend you try moment (https://momentjs.com/docs/#/displaying/difference/).
With that you can easilly get the difference in milliseconds:
const currentTime = moment();
const someTime = moment([2010, 1, 14, 15, 25, 50, 125]) // [year, month, day, hour, minute, second, millisecond]
const millisecondDifference = currentTime.diff(someTime);
and then use that difference to set interval (or use moment/Date to transform it to something)
You don't need to use a counter, and a counter will probably not give you the result you want as setInterval/setTimeout will not fire at exactly 1000ms.
You can subtract the start date from the current date every time setInterval calls your function. then format the result:
var start = new Date('2020-01-29 21:00:00');
startTime(){
this.interval = setInterval(() => {
this.display = new Date() - start;
return this.display;
}, 1000);
}
After subtracting the current date from the given date, in milliseconds, convert it to seconds, minutes , and hours and use setInterval to update the counter.
const date = Date.parse('30 Jan 2020 01:04:56 GMT+0300'); //your given date
const elem = document.getElementById('counter')
function count() {
let countFrom = (Date.now() - date); //get the difference with the current date
//convert to seconds, minutes and hours
seconds = parseInt((countFrom/1000) % 60)
minutes = parseInt((countFrom/(1000*60)) % 60)
hours = parseInt((countFrom/(1000*60*60)) % 24);
//append `0` infront if a single digit
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
let time = `${hours}:${minutes}:${seconds}`;
elem.textContent = time;
}
setInterval(count, 1000);
<div id='counter'>00:00:00</div>
I think this solves your problem
let now = Date.now();
let future = new Date('January 29, 2020 23:59:59').getTime();
let diffInSecond = Math.floor((future - now) / 1000);
var i = diffInSecond;
var interval = setInterval(function(){
if (i == 0) clearInterval(interval);
console.log(i);
i--;
},
1000);
Everything is in second you can format the result to show something like 00:31:29

Angular Date pipe, and a simple timer with Momentjs

I've got the following code, which is supposed to find the difference in milliseconds from one date, to another. It's meant to get the elapsed time since a view has been opened:
this.timer.start = new Date();
this.timer.intervalRef = setInterval(() => {
this.timer.elapsedTime = moment(new Date()).diff(this.timer.start)
}, 1000);
Then, in the template, it's shown as this:
{{ timer?.elapsedTime | date: 'hh:mm:ss' }}
It should display something like:
00:00:01
00:00:02
00:00:03
...
And the minutes and seconds part, work well. But the "hours" part, is starting always with 1, therefore giving me this output:
01:00:01
01:00:02
01:00:03
...
Can someone explain me what I've got wrong, and why it's working like this?
moment.diff return a duration and not a Date object.
You can use .duration and format with the desired output.
this.timer = {};
let start = moment(new Date());
let intervalRef = setInterval(() => {
let elapsedTime = moment(new Date()).diff(start)
let time = moment.duration(elapsedTime)
let hrs = ('0' + time.hours()).slice(-2);
let mins = ('0' + time.minutes()).slice(-2);
let secs = ('0' + time.seconds()).slice(-2);
this.timer.elapsedTime = `${hrs}:${mins}:${secs}`
console.log(this.timer.elapsedTime)
}, 1000);
<script src="https://momentjs.com/downloads/moment.js"></script>

How To Get The Sum of Two Times Using Moment.js?

I want to add two times like time1 = '00:05' and time2 = '10:00'. I want the result like the following after sum: result='10:05'. I used moment for that, this is what I used:
let x = moment.duration(moment(this.time1, "hh:mm A").add(moment(this.time2, "hh:mm A")));
let result = moment.utc(x.asMilliseconds()).format('HH:mm:ss');
but I got nothing, how can I do it?
You can't add time this way with moment because you are asking it to add two times, not a time plus a duration. If you want to add ten minutes, use the add() function with a duration.
moment(this.time2, "hh:mm A").add(10, 'minutes')
More here: https://momentjs.com/docs/#/manipulating/add/
It's not really clear in your question what 00:05 PM means. That doesn't look like a valid time. Moment will interpret it as 12:05pm, but it looks like you want to interpret it as 5 minutes. (That's the only way you get 10:05 as an answer). You can do this with moment if you don't include the PM part of the string.
moment.duration('00:05')
Is a duration of five minutes. You can add this to your time with:
moment('10:00 PM', '"hh:mm A"').add(moment.duration('00:05'))
// 22:05:00
Adding two periods works but it is currently not obvious in moment, how to format it like you want. Until they add format() to durations this will have to do:
var d = moment.duration('03:10:10').add(moment.duration('01:20:30'))
moment.utc(d.as('milliseconds')).format("HH:mm:ss")
// '04:30:40'
See Example For Add & Diff using moment.js .. cheers😀
// addTimes(["01:00", "00:30", "00:50"]) ---- 02:20
addTimes(times) {
let duration = 0;
times.forEach(time => {
duration = duration + moment.duration(time).as('milliseconds')
});
return moment.utc(duration).format("HH:mm")
}
// subtractTimes(["05:00", "00:30", "00:20"]) --- 04:10
subtractTimes(times) {
let totalDiff = 0
for (let i = 0; i < times.length; i++) {
let duration = moment.duration(times[i]).as('milliseconds')
if (i == 0) {
totalDiff = duration
}
if (i > 0) {
totalDiff = totalDiff - duration
}
}
return moment.utc(totalDiff).format("HH:mm")
}
function addTwoHours(firstTime = "20:40", secondTime = "18:40") {
firstTime = firstTime.split(':');
secondTime = secondTime.split(':');
const now = moment();
const expiration = moment().add({ hour: firstTime[0], minute: firstTime[1] }).add({ hour: secondTime[0], minute: secondTime[1] });
const diff = expiration.diff(now);
const diffDuration = moment.duration(diff);
return {
"years": diffDuration.years(),
"months": diffDuration.months(),
"days": diffDuration.days(),
"hours": diffDuration.hours(),
"minutes": diffDuration.minutes(),
"yourAnswer" : `${expiration.diff(now, 'hours')}:${diffDuration.minutes()}`
}
}
console.log(addTwoHours());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

Categories