Check if the time is within the last five minutes - javascript

I have a time displayed on my webpage, and im trying to do an action if the time value i have is 5 minutes or older than the current time.
var date1 = new Date(1625807904*1000); // 1625807904 is my date and time
var convert = date1.getDate()+"/"+(date1.getMonth()+1)+"/"+date1.getFullYear()+" "+date1.getHours()+ ":"+ (date1.getMinutes()<10?'0':'') + date1.getMinutes()+ ":"+(date1.getSeconds()<10?'0':'')+date1.getSeconds();
Just my concept
if ( convert < 5minutes or older than the current time){
**** do something ****
}
Thank you for your time !!!

You can subtract two Date in JavaScript. The default value is based on millisecond:
var date = new Date(1625807904*1000);
console.log('diffrences based on milliseconds', Date.now() - date)
console.log('diffrences based on minutes', (Date.now() - date) /(60 * 1000))
if((Date.now() - date) <= (5 * 60 * 1000))
{
console.log("your condition is meeted. Do your ACTION")
}

Related

Predefined functions for extracting "work hours" from two timestamps in JavaScript?

I have two timestamps and I must find the "working hours" in between these two timestamps where "working hours" is defined as 9:00 to 17:00 (9AM to 5PM).
Given the timestamps 2022-04-25 15:00:00 and 2022-04-27 10:00:00:
2022-04-25 15:00:00 -> 2 hours
2022-04-26 -> 8 hours (full day)
2022-04-27 10:00:00 -> 1 hour
So the total would be 11 working hours.
I know how to do this in SQL with the EXTRACT function but I'm not as adept in JavaScript and my search hasn't returned anything useful. Alternatively, I could add up the time that falls in the "work hours" given two timestamps but I want to check if there's some pre-defined function for this.
SQL equivalent: SQL extract hour from timestamp
Native API?
There is no easy API for this in JavaScript. You have to write such functionality yourself.
Possible solution
Here one approach to do that:
/**
* Calculate working hours in a given time range. Does not take weekends into account.
* #param {Date} start start Date of range
* #param {Date} end end Date of range
* #param {number} whStart start of working hours
* #param {number} whEnd end of working hours
* #returns object containing total working hours in range and working hours per day in milliseconds (ms) and hours (h)
*/
function workingHoursInRange(start, end, whStart, whEnd) {
let totalTime = 0;
// get day difference between start and end date
const dayDiff = end.getDate() - start.getDate() + 1;
let diff = 0;
const workingHoursPerDay = [...Array(dayDiff)].map((_, i) => {
// first day (start time till end of working hours)
if (i === 0) diff = firstDay(start, whStart, whEnd);
// last day (start of working hours till end date)
else if (i === dayDiff - 1) diff = lastDay(end, whStart, whEnd);
// days inbetween are full days
else diff = (whEnd - whStart) * 1000 * 3600;
totalTime += diff;
return diff;
});
return {
workingHoursPerDay: {
ms: workingHoursPerDay,
h: workingHoursPerDay.map((it) => it / (1000 * 3600)),
},
totalHours: {
ms: totalTime,
h: totalTime / (1000 * 3600),
},
};
}
/**
* Calculate working hours on first day of a date range
* #param {Date} date date
* #param {number} whStart start of working hours
* #param {number} whEnd end of working hours
* #returns working hours in milliseconds
*/
function firstDay(date, whStart, whEnd) {
const minEnd = new Date(
date.getFullYear(),
date.getMonth(),
date.getDate(),
whEnd
);
const maxStart = new Date(
Math.max(
new Date(date.getFullYear(), date.getMonth(), date.getDate(), whStart),
date
)
);
return minEnd - maxStart;
}
/**
* Calculate working hours on last day of a date range
* #param {Date} date date
* #param {number} whStart start of working hours
* #param {number} whEnd end of working hours
* #returns working hours in milliseconds
*/
function lastDay(date, whStart, whEnd) {
const maxStart = new Date(
date.getFullYear(),
date.getMonth(),
date.getDate(),
whStart
);
const minEnd = new Date(
Math.min(
new Date(date.getFullYear(), date.getMonth(), date.getDate(), whEnd),
date
)
);
return minEnd - maxStart;
}
// Test
const workingHoursStart = 9;
const workingHoursEnd = 17;
const input = [
{
start: new Date("2022-04-25 01:00:00"),
end: new Date("2022-04-27 10:00:00"),
},
{
start: new Date("2022-04-25 12:00:00"),
end: new Date("2022-04-27 10:00:00"),
},
{
start: new Date("2022-04-26 12:33:00"),
end: new Date("2022-04-26 16:05:00"),
},
];
// calculate working hours for all ranges
const result = input.map(({ start, end }) =>
workingHoursInRange(start, end, workingHoursStart, workingHoursEnd)
);
// log result
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Please note: currently this implementation does not take into account weekends but with some small adjustments this could be considered as well.
Essentially the idea is to split a date range into three parts:
first day
last day
days inbetween
The working hours on the first day will be determines by the maximum of the working hours start and the actual start date. For the last day the minimum of working hours end and end date will determine the total working hours on that day. For all days inbetween are full work days and we can just use the difference between working hours end and working hours start to calculate the total working hours.
This approach avoids possible caveats with date arithmetic such as daylight saving.
So I don't know if there are any predefined functions or anything for this. You've said you've searched and didn't find a solution. So I assume there aren't any.
A fiddle
That's why I started fiddling! I liked the challenge. ;-) The code below does basically do what you want in the example I guess. It's more a proof of concept.
But that's also why there are still a few things that you need cover from here an out in a real use-case:
I didn't account for minutes for example
I didn't account for weekends
I didn't account for two timestamps that are between different months (from april 25 to may 2 for example)
Breaks?
But that's just some fine-tuning!!
function calcWorkedHours(start, end) {
let workedHours = 0;
let startDateTime = new Date(start);
let endDateTime = new Date(end);
let workDate = startDateTime.getDate();
while (workDate <= endDateTime.getDate()) {
if (workDate === startDateTime.getDate()) {
// if they started before 17 oclock.
if (startDateTime.getHours() < 17) {
let workedHoursStartDate = 17 - startDateTime.getHours();
console.log(workedHoursStartDate);
workedHours += workedHoursStartDate;
}
}
else if (workDate === endDateTime.getDate()) {
// if they finished after 9 oclock.
if (startDateTime.getHours() > 9) {
let workedHoursEndDate = endDateTime.getHours() - 9;
console.log(workedHoursEndDate);
workedHours += workedHoursEndDate;
}
}
else {
let workedHoursFullDay = 8;
console.log(workedHoursFullDay);
workedHours += workedHoursFullDay;
}
workDate++;
}
console.log("Worked hours: " + workedHours);
return workedHours;
}
calcWorkedHours("2022-04-25 15:00:00", "2022-04-27 10:00:00");

set javascript date object to before 30 days

Lets say now the date is 10/07/2015, ie If I create a javascript date object like as shown below I will get todays date as 07/10/2015
var now = new Date();
So if the date is 10/07/2015 I want 30 days back date i.e 07/09/2015.
I did like as shown below but for that I got 31/08/2015
var now = new Date();
now .setDate(-30);
Can anyone please tell me some solution for this
You can try like this:
Date.today().add(-30).days();
And if you want then moment.js is really good when dealing with dates
moment().subtract(30, 'days');
And if you dont want to use any library then
var now = new Date()
var prev = new Date().setDate(now.getDate()-30)
You could have simply use now.getDate():
var now = new Date();
document.write(now);
now.setDate(now.getDate() - 30);
document.write("<br/>");
document.write(now);
A Date object internally contains a value that corresponds to the number of milliseconds passed since 1 January, 1970 UTC.
As such, using this value (accessible via Date.prototype.valueOf()) you can add or subtract any size of "simply calculated" time interval. By simply calculated I mean anything that can be calculated using simple arithmetics, such as (for example..) "1 day 4 hours and 2 minutes" is equal to (((1 * 24) + 4) * 60 + 2) * 60 * 1000. You can add / subtract that to any starting time and create a new Date object:
var startDate = new Date();
var newDate = new Date(startDate.valueOf() + ((((1 * 24) + 4) * 60 + 2) * 60 * 1000));
alert(newDate);
In the specific case of days offset, simply use this formula:
days * 24 * 60 * 60 * 1000

Get time (hour, minute) from a non-local ISO8601 string with moment

I would like to get the time of an ISO8601 string in the specified timezone.
However, whenever I grab the moment object of the ISO8601 string, it converts everything to my machine's local time.
E.g. when I do moment("2015-09-15T07:55+02:00").hours(), it returns 1 since it converted it to 2015-09-15T01:55:00-04:00".
How do I make it so that it returns 7 for hours?
I think this will help:
http://momentjs.com/docs/#/parsing/special-formats/
moment("2010-01-01T05:06:07", moment.ISO_8601);
not sure about moment, but here's my converter for the eastern time zone, if it helps...
getServerDate: function(dateValue) {
var dateJan;
var dateJul;
var timezoneOffset;
// Get dates for January and July
dateJan = new Date(dateValue.getFullYear(), 0, 1);
dateJul = new Date(dateValue.getFullYear(), 6, 1);
// Get timezone offset
timezoneOffset = Math.max(dateJan.getTimezoneOffset(), dateJul.getTimezoneOffset());
// Check if daylight savings
if (dateValue.getTimezoneOffset() < timezoneOffset) {
// Adjust date by 4 hours
dateValue = new Date(dateValue.getTime() + ((1 * 60 * 60 * 1000) * 4));
} else {
// Adjust date by 5 hours
dateValue = new Date(dateValue.getTime() + ((1 * 60 * 60 * 1000) * 5));
}
return dateValue;
},

count down to multiple moments, how?

I'm creating a site for my neighbor who has a Christmas light show.
The show runs every year from 6 December till 1 January twice an evening: at 6.30pm and at 8.00pm.
We want to add a countdown on the website which says:
next show: 00:00:00 (hh:mm:ss)
But how do I do that. When I search for it on the web every one says that I have to use an API for a countdown.
But they just use one date to count down to, so I think I have to write one myself in JavaScript.
Can anyone help with that?
I guess I have to use many if/else statements, starting with "is the month 1, 12 or something else?", followed by "has it yet been 18.30?" (I want 24-hours) and "has it already been 20.00" and so on.
But is there a better way, because this seems a lot of work to me.
JavaScript has a built-in date object that makes dealing with dates and times a bit less manual:
MDN documentation for JavaScript's date object
If you supply no arguments to its constructor, it'll give you the current date (according to the end user's computer):
var now = new Date();
You can set it to a specific date by supplying the year, month (zero-indexed from January), day, and optionally hour, minute and second:
var now = new Date();
var first_show = new Date(now.getFullYear(), 11, 6, 18, 30);
You can use greater- and less-than comparisons on these date objects to check whether a date is after or before another:
var now = new Date();
var first_show = new Date(now.getFullYear(), 11, 6, 18, 30);
alert(now < first_show);// Alerts true (at date of writing)
So, you could:
Create date objects for the current date, and each show this year (and for the 1st Jan shows next year)
Loop through the show dates in chronological order, and
Use the first one that's greater than the current date as the basis for your countdown.
Note: you should use something server-side to set now with accurate parameters, instead of just relying on new Date(), because if the end-user's computer is set to the wrong time, it'll give the wrong result.
Here's an example that will count down for 4 hours starting now() :
<script type="text/javascript">
var limit = new Date(), element, interval;
limit.setHours(limit.getHours() + 4);
window.onload = function() {
element = document.getElementById("countdown");
interval = setInterval(function() {
var now = new Date();
if (now.getTime() >= limit.getTime()) {
clearInterval(interval);
return;
}
var diff = limit.getTime() - now.getTime();
var hours = parseInt(diff / (60 * 60 * 1000));
diff = diff % (60 * 60 * 1000);
minutes = parseInt(diff / (60 * 1000));
diff = diff % (60 * 1000);
seconds = parseInt(diff / 1000);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
miliseconds = diff % 1000;
miliseconds = miliseconds.toString().substring(0, 2);
element.innerHTML = hours + ":" + minutes + ":" + seconds + ":" + miliseconds;
}, 10);
}
See it live here

How to round to nearest hour using JavaScript Date Object

I am working on a project that requires a time in the future to be set using the Date object.
For example:
futureTime = new Date();
futureTime.setHours(futureTime.getHours()+2);
My questions is; once the future date is set, how can I round to the closest full hour and then set the futureTime var with it?
For example:
Given 8:55 => var futureTime = 9:00
Given 16:23 => var futureTime = 16:00
Any help would be appreciated!
Round the minutes and then clear the minutes:
var date = new Date(2011,1,1,4,55); // 4:55
roundMinutes(date); // 5:00
function roundMinutes(date) {
date.setHours(date.getHours() + Math.round(date.getMinutes()/60));
date.setMinutes(0, 0, 0); // Resets also seconds and milliseconds
return date;
}
The other answers ignore seconds and milliseconds components of the date.
The accepted answer has been updated to handle milliseconds, but it still does not handle daylight savings time properly.
I would do something like this:
function roundToHour(date) {
p = 60 * 60 * 1000; // milliseconds in an hour
return new Date(Math.round(date.getTime() / p ) * p);
}
var date = new Date(2011,1,1,4,55); // 4:55
roundToHour(date); // 5:00
date = new Date(2011,1,1,4,25); // 4:25
roundToHour(date); // 4:00
A slightly simpler way :
var d = new Date();
d.setMinutes (d.getMinutes() + 30);
d.setMinutes (0);
Another solution, which is no where near as graceful as IAbstractDownvoteFactory's
var d = new Date();
if(d.getMinutes() >= 30) {
d.setHours(d.getHours() + 1);
}
d.setMinutes(0);
Or you could mix the two for optimal size.
http://jsfiddle.net/HkEZ7/
function roundMinutes(date) {
return date.getMinutes() >= 30 ? date.getHours() + 1 : date.getHours();
}
As a matter of fact Javascript does this default which gives wrong time.
let dateutc="2022-02-17T07:20:00.000Z";
let bd = new Date(dateutc);
console.log(bd.getHours()); // gives me 8!!!!!
it is even wrong for my local time because I am GMT+2 so it should say 9.
moment.js also does it wrong so you need to be VERY carefull
Pass any cycle you want in milliseconds to get next cycle example 1 hours
function calculateNextCycle(interval) {
const timeStampCurrentOrOldDate = Date.now();
const timeStampStartOfDay = new Date().setHours(0, 0, 0, 0);
const timeDiff = timeStampCurrentOrOldDate - timeStampStartOfDay;
const mod = Math.ceil(timeDiff / interval);
return new Date(timeStampStartOfDay + (mod * interval));
}
console.log(calculateNextCycle(1 * 60 * 60 * 1000)); // 1 hours in milliseconds

Categories