checking if a current time falls in a particular interval in javascript - javascript

EDIT: Please take care to introduce UTC timing in your answer. Since doing things on client side will lead to different time zones.
In javascript, i can get the current time, hour and minute as follows:
var currentTime = new Date();
var currentHour = currentTime.getHours();
var currentMinute = currentTime.getMinutes();
Now i have to perform a task only if the current time false in an interval with a fixed time.
Say there is a fixed time 10:30 AM. Users can perform a certain task iff the current time, is 4 hours behind the current time or 1 hour ahead of the fixed time.
meaning users can perform the task from 6:30 AM to 11:30 AM.
I tried getting the current hours and doing
start = fixed_time - 4;
end = fixed_time + 1;
if currentHour< end or currentHour > start{
do some stuff;
}
But this ignores the minutes, how to take care of that?
Otherwise, how could i figure if the current time lies between 6:30 AM and 11:30 AM?

var currentTime = new Date();
var startTime = new Date(2012, 3, 8, 6, 30, 0, 0); //6:30am today
var endTime = new Date(2012, 3, 8, 11, 30, 0, 0); //11:30am today
if ((currentTime.getTime() > startTime.getTime()) && (currentTime.getTime() < endTime.getTime())
{
//current time is between start and end so do what you need to do
}
If you need it to be more dynamic you can
var currentTime = new Date();
var startTime = new Date();
startTime.setHours(6);
startTime.setMinutes(30);
var endTime = new Date();
endTime.setHours(11);
endTime.setMinutes(30);
if ((currentTime.getTime() > startTime.getTime()) && (currentTime.getTime() < endTime.getTime())
{
//current time is between start and end so do what you need to do
}

You can use getTime() method which returns the number of milliseconds since midnight Jan 1, 1970:
currentTime = (new Date()).getTime();
Then all you need is to calculate the difference between your fixed time and current time in milliseconds. 4 hours equals to 14,400,000 (4*60*60*1000) milliseconds.

You can compare dates to one another. So, using the current date and time you can compare that to dates with a fixed time set. Something like:
var now = new Date
,lower = new Date
,upper = new Date;
//determine limits
lower.setHours(6);
lower.setMinutes(30);
upper.setMinutes(30);
upper.setHours(11);
//tests
now = new Date('2012/04/08 22:00');
console.log(now >= lower && now <= upper); //=> false
now = new Date('2012/04/08 07:00');
console.log(now >= lower && now <= upper); //=> true

var startTime = '01 AM'; // or var startTime = '01:00 AM';
var endTime = '09 AM'; // or var startTime = '09:00 AM';
var now = new Date();
if(now < convert_time(endTime) && now > convert_time(startTime)){
alert("With in a range");
}else{
alert("Out of range");
}
function convert_actual_time(time) {
if(time.indexOf(" ") != -1){
split1 = time.split(" ");
splitTime = split1[0];
splitZone = split1[1];
}
if(splitTime.indexOf(":") != -1){
split2 = splitTime.split(":");
setHours = split2[0];
setMins = split2[1];
}else{
setHours = splitTime;
setMins = "00";
}
if(splitZone.toLowerCase() == "pm"){
setHours = parseInt(setHours)+12;
}
date = new Date();
date.setHours(setHours);
date.setMinutes(setMins);
return date;
}
Try with this code

Related

Can I use comparison and logical operators for time inputs in Javascript? [duplicate]

I'm trying to write a statement that says "if time is this and less than that then". I can use get hours and get min. However, I'm having problems combining a time such as 9:30.
Example,
var now = new Date();
var hour = now.getHours();
var day = now.getDay();
var mintues = now.getMinutes();
if (day == 0 && hour >= 9 && hour <= 11 && mintues >= 30) {
document.write(now);
}
This only if the time is less between 9:30 10. As soon as the clock hits 10 the minutes are then < 30 and the script breaks.
Any thoughts on how to better incorporate the time function to make this theory work?
Thanks,
use new Date().getTime() returns milliseconds for much easier comparison. This way there is no need to check hour, min, second, millisecond. Fiddle link
var d930 = new Date(2010, 12, 21, 9, 30, 0, 0), // today 9:30:00:000
d931 = new Date(2010, 12, 21, 9, 31, 0, 0), // today 9:31:00:000
t930 = d930.getTime(),
t931 = d931.getTime();
console.log(t931 > t930);
This way your code can check against a static 9:30 time.
var time930 = new Date(2010, 12, 21, 9, 30, 0, 0).getTime(),
sunday = 0,
now = new Date();
if(now.getDay() == sunday && now.getTime() >= time930){
/* do stuff */
}
You have a few typos and basic javascript errors.
Might wanna brush up on the basics.
W3Schools is where I learned all I know.
It works fine if you fix them...
var now = new Date();
var hour = now.getHours();
var day = now.getDay();
var minutes = now.getMinutes();
if(day == 0 && hour == 9 && minutes < 30 && minutes > 10 || day == 0 && hour == 9)
document.write('Time is between 9:10 and 9:30');
Think of the if statement as basic logic.
If the day is Sunday(0)
AND the hour is 9
AND the minutes are greater than 10
AND the minutes are less than 10
OR the day is Sunday(0)
AND the hour is before 9.
var now = new Date();
var closeTime = new Date();
closeTime.setHours(9); closeTime.setMinutes(30);
console.log(now, closeTime, now.getTime() >= closeTime.getTime());
close time is based on today, then we just change the hours and minutes to 9:30.
I made this solution simple and easy to read (thus easy to adjust).
// we need a function that makes hours and minutes a two digit number
Object.prototype.twoDigits = function () {
return ("0" + this).slice(-2);
}
// get current date and time
let now = new Date();
// compile the current hour and minutes in the format 09:35
timeOfDay = now.getHours().twoDigits() + ':' + now.getMinutes().twoDigits();
// test if timeOfDay is within a given time frame
if ('09:30' <= timeOfDay && timeOfDay <= '11:30') {
console.log('inside time frame');
} else {
console.log('outside time frame');
}
I had a similar problem to solve today, I setup a little component that returns if a place of business is open or not. Got the time by dividing the minutes by 100 then adding it to the hours. So 8:30 is represented as 8.3
let d = new Date()
let day = d.getDay()
let hours = d.getHours()
let minutes = d.getMinutes() / 100
let time = hours + minutes
if (day == 1) {
if (time > 8.3 && time < 17.3) {
setIsOpen(true)
} else {
setIsOpen(false)
}
}
if the hour is less than 9, true
or
if hour is 9 and minutes lt 30, true
so that would look like
if ((hour < 9) || (hour == 9 && minutes < 30))
Use words to figure out your logic. Symbols are just shortcuts.
One way is to do a direct comparison on date objects. Choose an arbitrary year, month and day, and then incorporate your times as follows:
var older = new Date("1980-01-01 12:15");
var newer = new Date("1980-01-01 12:30");
if (newer > older){
alert("Newer time is newer");
} else {
alert ("The time is not newer");
}
The MDC documentation on the Date object will help with some more details. The bottom line is that if you want to compare times, you don't actually need to call any methods on the objects, and it's possible to directly compare them. The date() object can take a variety of strings to assign a new time to the returned instance, these are from the MDC documentation:
today = new Date();
birthday = new Date("December 17, 1995 03:24:00");
birthday = new Date(1995,11,17);
birthday = new Date(1995,11,17,3,24,0);
As you can see, it's pretty simple. Don't complicate, and have a look through the documentation :)
While we're here, here's a test using your example:
var base = new Date("1980-01-01 9:30");
var test = new Date("1980-01-01 9:30:01");
if (test >= base){
alert("test time is newer or equal to base time");
} else {
alert ("test time is older than 9.30");
}
Try this:
var now = new Date();
var hour = now.getHours();
var mintues = now.getMinutes();
if(
(hour*60 + mintues) > 570 &&
hour <= 11
)
{
document.write(now);
}
I don't quite fully understand your question but hope this helps.
c = new Date();
nhour = c.getHours();
nmin = c.getMinutes();
if(nmin <= 9) {
nmin = "0" + nmin;
}
if(nhour <= 9) {
nhour = "0" + nhour;
}
newtime = nhour + "" + nmin;
if(newtime <= 0930){
alert("It is before 9:30am or earlier");
}

Add timezone to this js schedule?

I have this javascript code to schedule when certain divs show, but the problem I'm having is it's not using device time or our time zone. I really need it to be assigned to the central time zone.
function displayMsg() {
var currentTime = new Date();
function toUTC(date) {
return Date.UTC(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds()
);
}
toUTC(currentTime);
var startMsg1Time = new Date("2021-10-03T11:15:00Z");
var endMsg1Time = new Date("2021-10-08T14:33:00Z");
var startMsg2Time = new Date("2021-11-15T23:00:01Z");
var endMsg2Time = new Date("2021-11-16T22:59:59Z");
if (currentTime.getTime() > startMsg1Time.getTime() && currentTime.getTime() <= endMsg1Time.getTime()) {
$('.Msg1').show();
} else if (currentTime.getTime() > endMsg1Time.getTime) {
$('.Msg1').hide();
}
if (currentTime.getTime() > startMsg2Time.getTime() && currentTime.getTime() <= endMsg2Time.getTime()) {
$('.Msg2').show();
} else if (currentTime.getTime() > endMsg2Time.getTime) {
$('.Msg2').hide();
}
}
displayMsg();
As a side note, this isn't completely achieving what I need. I'm trying to have a message show every Sunday from 8:30am-11:15am and Friday from 7:00pm-8:15pm. I was going to use this method and just create a schedule a month at a time, but if anyone can recommend a better approach then I'm happy to hear.
You can do something like in below snippet , i.e , giving only minutes and hour and then checking if day = 1 (Monday) . I have set alarm time to 11:25 PM to 11:35 PM(Monday) (You can set any)
Use update of alarm according to need , here I have set 1sec using setInterval
Below snippet is for demo only , you can have any number of messages and alarm and specify day of alarm to come up or month (and can be year to which alarm ring)
setInterval(function() {
var d = new Date();
var Msg1Day = d.getDay();
var Msg1TimeStart = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 25, 0, 0)
var Msg1TimeEnd = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 35, 0, 0)
if (Msg1Day === 1) {
if (d >= Msg1TimeStart && d <= Msg1TimeEnd) {
document.querySelector("#demo").innerHTML = "Alarm is ON"
document.querySelector(".Msg1").innerHTML = "You already enjoyed Sunday, It's Monday Time and soon will Be Tuesday(Alarm is from 11:25 PM - 11:35 PM)"
} else {
document.querySelector("#demo").innerHTML = "Alarm is OFF"
document.querySelector(".Msg1").innerHTML = ""
}
} else {
document.querySelector("#demo").innerHTML = "Today is not monday"
}
}, 1000);
<div class="Msg1"></div>
<div id="demo">Alaram status will be in 1sec and will be updated every second</div>

How to format a schedule array with start and end times in a for() in javascript?

My goal is to have the timer start at the designated times (which it does), but I do not want the dates (Jan 29, 2019) I just want the times, so that I do not have to update the date every single day. Any suggestions on how I can change the for () to work for times and not dates?
I have tried deleting just the date and leaving the time and it will not work.
var schedule = [
['Jan 29, 2019 20:43:00', 'Jan 29, 2019 21:48:05']
]
<!-- Mainly this part -->
for(var i=0; i<schedule.length; i++){
var startDate = schedule[i][0];
var endDate = schedule[i][1];
// put dates in milliseconds for easy comparisons
var startMs = Date.parse(startDate);
var endMs = Date.parse(endDate);
var currentMs = Date.parse(new Date());
// if current date is between start and end dates, display clock
if(endMs > currentMs && currentMs >= startMs ){
initializeClock('clockdiv', endDate);
openRequestedPopup();
myStopFunction();
setInterval(function(){window.location.reload(5);}, 306000);
setTimeout(function () { windowObjectReference.close();}, 305000);
}
Only display timer with date and time and I just want the timer to display with just the start and end times.
Based on what I commented, if that is the case something like this should work:
const schedule = [
['Jan 29, 2019 20:43:00', 'Jan 29, 2019 21:48:05']
]
for(let i=0; i<schedule.length; i++){
// pull them straight into Date objects
const startDate = new Date(schedule[i][0]);
const endDate = new Date(schedule[i][1]);
// Make a new Date for setting it for today, then set the hours based off the schedule
let startTime = new Date();
startTime.setHours(startDate.getHours(), startDate.getMinutes(), startDate.getSeconds());
let endTime = new Date();
endTime.setHours(endDate.getHours(), endDate.getMinutes(), endDate.getSeconds());
// Easier way to just get the ms and then the same check
const currentMs = Date.now();
if(endTime.valueOf() > currentMs && currentMs >= startTime.valueOf() ){
// Whatever we are doing when it's inside the window
}
}
var schedule = [
['Jan 30, 2019 10:40:00', 'Jan 30, 2019 12:12:05']
];
for(var i=0; i<schedule.length; i++){
var startDate = schedule[i][0];
var endDate = schedule[i][1];
// put dates in milliseconds for easy comparisons
var startMs = Date.parse(startDate);
var endMs = Date.parse(endDate);
var currentMs = Date.parse(new Date());
// if current date is between start and end dates, display clock
if( currentMs >= startMs && currentMs<endMs){
var id = setInterval(function(){ printTime(); }, 1000);
function printTime(){
var time = new Date();
currentMs = time.getTime();
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();
document.write(hours + " " + minutes+" " + seconds+" ");
if(currentMs>=endMs)
clearInterval(id);
}
}
}
check this it's may be helpful to you...
keep learning.....

How do I populate a Javascript array with a series of dates from a loop?

Here's the code I'm working on:
function populateDates() {
var start = new Date(2017, 7, 13);
var end = new Date(2017, 8, 3);
var tempDate = start;
var endPlus90 = end.setDate(end.getDate() + 90);
var today = new Date();
var array = [];
for(var d = start; d < today || d < endPlus90; d.setDate(d.getDate() + 1)){
if (d.getDay() !== 0 && d.getDay() !== 6){
array.push([d]);
}
}
return array;
}
var future = new Date();
future.setDate(future.getDate() + 90);
console.log(populateDates(new Date(), future));
Basically, what I'm trying to do is, given an arbitrary start and end date, generate a list of dates, excluding weekends, from the start date to either 90 days after the end date, or the current date, whichever is earlier. The current function generates an array that is all identical dates which are 90 days after the end date. I'm not very familiar with Javascript, so I'm not sure what's going wrong here. I suspect that the way I'm pushing the variable to the array is incorrect.
The problem comes with your usage of setDate which returns
The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date (the Date object is also changed in place).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate
Wrap that setDate line in a new Date() and your code should run just fine.
As others pointed out the reason the array had multiples of the same date is because you were pushing references to the same single date object, and reassigning that object's date, which was updating it each of these references. By creating a new Date with new Date() you are creating a new object with its own reference.
Try this out. You need to initialize the d to a new Date every time. You can't just change the day. You also need to put new Date() around end.setDate(). setDate() returns milliseconds.
function populateDates(start, end) {
var tempDate = start;
var endPlus90 = new Date(end.setDate(end.getDate() + 90));
var today = new Date();
var array = [];
for(var d = tempDate; d < endPlus90; d = new Date(d.setDate(d.getDate() + 1))){
if(d >= today) { // Stop counting dates if we reach the current date
break;
}
if (d.getDay() !== 0 && d.getDay() !== 6){
array.push([d]);
}
}
return array;
}
var future = new Date(); // As of 10/18/2017
future.setDate(future.getDate() + 90);
console.log(populateDates(new Date(2017, 9, 1), future)); // Prints 13 days as of 10/18/2017
console.log(populateDates(new Date(2016, 9, 1), future)); // Prints 273 days

How to calculate ms since midnight in Javascript

What is the best way to calculate the time passed since (last) midnight in ms?
Create a new date using the current day/month/year, and get the difference.
var now = new Date(),
then = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
0,0,0),
diff = now.getTime() - then.getTime(); // difference in milliseconds
A bunch of answers so here another:
var d = new Date(), e = new Date(d);
var msSinceMidnight = e - d.setHours(0,0,0,0);
As a function:
function getMsSinceMidnight(d) {
var e = new Date(d);
return d - e.setHours(0,0,0,0);
}
alert(getMsSinceMidnight(new Date()));
Many answers except RobG's (recommended answer), Kolink's and Lai's are wrong here
Let's look closer together
First mistake
OptimusCrime and Andrew D. answers:
As Mala sugested, if the daylight saving correction was applied the nearest midnight, we get incorrect value. Let's debug:
Suppose it's last Sunday of March
The time is fixed at 2 am.
If we see 10 am on the clock, there's actually 11 hours passed from midnight
But instead we count 10 * 60 * 60 * 1000 ms
The trick is played when midnight happens in different DST state then current
Second mistake
kennebeck's answer:
As RobG wrote, the clock can tick if you get the system time twice. We can even appear in different dates sometimes. You can reproduce this in a loop:
for (var i = 0; true; i++) {
if ((new Date()).getTime() - (new Date()).getTime()) {
alert(i); // console.log(i); // for me it's about a 1000
break;
}
}
Third is my personal pitfall you could possibly experience
Consider the following code:
var d = new Date(),
msSinceMidnight = d - d.setHours(0,0,0,0);
msSinceMidnight is always 0 as the object is changed during computation before the substraction operation
At last, this code works:
var d = new Date(),
msSinceMidnight = d.getTime() - d.setHours(0,0,0,0);
Simpler to write, if you don't mind creating two dates.
var msSinceMidnight= new Date()-new Date().setHours(0,0,0,0);
var d=new Date();
// offset from midnight in Greenwich timezone
var msFromMidnightInGMT=d%86400000;
// offset from midnight in locale timezone
var msFromMidnightLocale=(d.getTime()-d.getTimezoneOffset()*60000)%86400000;
var today = new Date();
var d = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0, 0);
var difference = today.getTime() - d.getTime();
Seconds since midnight would simply be to display the time, but instead of using hours:minutes:seconds, everything is converted into seconds.
I think this should do it:
var now = new Date();
var hours = now.getHours()*(60*60);
var minutes = now.getMinutes()*60;
var seconds = now.getSeconds();
var secSinceMidnight = hours+minutes+seconds;

Categories