Determine whether the current time exceeds a certain time of day

While this may have been asked before, I am struggling to find an answer. How can I determine if the current time is after 17:30 each day?

In my scenario, I need to check if it is past 17:30 on Monday to Friday, and if it is Saturday, I need to check if it is past 15:30.

I would prefer to use Moment.js for this task.

Answer №1

Check out this code snippet using moment.js

function checkTime() {
  var currentTime = moment();
  var timeToCheck = (currentTime.day() !== 0)?17:15;
  var dateToCheck = currentTime.hour(timeToCheck).minute(30);
  
  return moment().isAfter(dateToCheck);
}

console.log(checkTime())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>

Answer №2

Don't bother with a large plugin, you can simply use Date() to check the time:

var curTime = new Date();
var day = curTime.getDay();
curTime = parseInt(curTime.getHours() + "" + ("0" + curTime.getMinutes()).substr(-2) + "" + ("0" + curTime.getSeconds()).substr(-2));

if ((curTime > 173000 && day > 0 && day < 6) || (curTime > 153000 && day <= 0 && day >= 6))
  console.log("It's a good time!");
else
  console.log("It's not a good time!");

If this solution fails in any scenario, please let me know!

Answer №3

Here is a different method using the moment.js library:

let currentTime = moment();
let currentDayOfWeek = currentTime.day();
let closingTimeToday = moment('17:30','HH:mm');
let emergencyClosingTimeToday = moment('15:30','HH:mm');
let isOpen = currentDayOfWeek > 0 && currentDayOfWeek < 7 ? currentTime.isSameOrAfter(closingTimeToday) : currentTime.isSameOrAfter(emergencyClosingTimeToday);

if (isOpen) { ... }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Load Jquery Ajax every second interval

I discovered this script on the W3 school website. <script> $(document).ready(function(){ setInterval(function(){ $("#div1").load("demo_test.txt"); }, 30000); // Load demo_test.txt every 30 seconds }); </script> The purpose of ...

In what way can I ensure that the value of currentIndex is consistently set to 0 before each calculation?

Is there a way to set the Value of currentIndex to always be 0? The calculation of (CRANK1 + CRANK2) + (DRANK1 + DRANK2) should result in (0 + selected amount), but it is currently calculating as (selected amount + selected amount). Any assistance would ...

Is there a way to retrieve all documents based on the start and end of a specific day?

One common issue I am facing involves submitting a date to my nodejs server in a specific format

 2018-11-02T00:36:00+05:30 // The actual time should be 12:36AM However, when examining the document in my database (using studio 3T), the format appear ...

Tips for inheriting and overriding controller methods in AngularJS with Java as the base language:

I have a simple controller and I want to create a new controller that is very similar to it, but without copying too much code. angular.module('test').controller('parentController', parentController); parentController.$inject = [' ...

The setInterval function is active in various components within Angular 6

Recently, I started using Angular(6) and incorporated the setInterval function within a component. It's functioning properly; however, even after navigating to another route, the setInterval continues to run. Can someone help me determine why this is ...

I am having trouble getting the hamburger menu to open on my website with Bootstrap. Can anyone help me troubleshoot this issue and find

Why isn't my navbar hamburger menu opening on smaller screens? Despite the links displaying correctly on larger screens, I am unable to get the navbar to open. I've tried various troubleshooting methods such as changing tags in the header, deleti ...

What could be causing the Jquery keydown event to only trigger every other key press?

Recently, I have put together a thumbnail gallery that can be navigated using left and right arrows. I have noticed that while the right arrow works smoothly, the left arrow only seems to navigate to the previous thumbnail every other time. Can someone ple ...

Missing Values in jQuery Variable

I'm having trouble with adding a link after a block of text. Although the links render fine, the href tag seems to disappear. var eventstuff = data.text; var eventElement = $("<div class='well well-sm eventsWells'>"); var deleteButton ...

Is there a way to extract the value of a child object from an object within the MUI Datagrid

Using the following method: useEffect(() => { PetService.getAll("/pets") .then(response => { setData(response.content); }) }, [setData]); The response obtained is as follows: { "timestamp": 167818109 ...

Embed a physical entity within another physical entity

On my webpage, I have 2 toggle buttons - "Leaderboard" and "MedalTally". The layout looks like this: https://i.sstatic.net/IohqA.png Here are the codes for the above page: *, *:before, *:after { box-sizing: border-box; } html { overflow-y: scrol ...

A guide to exporting a class in ReactJS

I am currently working on exporting some classes from my music player file - specifically playlist, setMusicIndex, and currentMusicIndex. const playlist = [ {name: 'September', src: september, duration: '3:47'}, {name: 'hello ...

Fetching an attribute from an array using a URL parameter in JavaScript

I am attempting to filter a JSON array based on a value from a URL and extract the vernacularName attribute. While debugging in F12, I can successfully retrieve the correct variable using record[0].vernacularName;, however, the code below still does not wo ...

Incorporating URL parameters into an HTML form using JavaScript or jQuery

I need to pass variables in the URL to populate an HTML and Liquid form and then submit it. Here is an example URL: http://www.example.com/[email protected] &customer_password=123456 I came across this question which is somewhat related to what ...

Ways to avoid unintentional removal of contenteditable unordered lists in Internet Explorer 10

How can I create a contenteditable ul element on a webpage while avoiding the issue in Internet Explorer 10 where selecting all and deleting removes the ul element from the page? Is there a way to prevent this or detect when it happens in order to insert ...

Is it possible to adjust the background color based on the current time of day?

I have successfully designed a visually appealing website using HTML5, CSS, and Bootstrap. I am interested in finding a way to automatically change the background color and navigation bar selection color based on the time of day - blue during the day and d ...

How can I avoid OnServerClick when using OnClick?

Currently, I am working with ASP.NET and have a link that utilizes both onclick and onserverclick events. While both are crucial, I would like the onclick event to override the onserverclick event if possible. This is the code snippet I am currently exper ...

Tips for extracting key values from an array of objects in Typescript

I am working with an array called studyTypes: const studyTypes = [ { value: "ENG", label: "ENG-RU", }, { value: "RU", label: "RU-ENG", }, ]; Additionally, I have a state variable set ...

Using JavaScript to retrieve the text value of a custom button

Recently, I encountered a peculiar button in my code: <button type="button" id="ext-gen26" class=" x-btn-text">button text here</button> Despite its unique appearance, I am struggling to locate it based on the tex ...

Issue at hand: Unexpected error 500 encountered while sending AJAX request to PHP script through

UPDATE: Issue Resolved! I want to extend my gratitude to everyone who directed me to the error log files for assistance. The community here is truly incredible and I was able to get a resolution much quicker than anticipated. It's quite embarrassing, ...

alert message specific to a certain page (triggered by clicking the back button, accessing the menu, or pressing a particular button

I am facing a dilemma with a web application that allows the administrator (my client) to edit orders. They have expressed a need for warnings to prevent the loss of work. These warnings should trigger if you click on: Buttons such as Save, Work Order, D ...