A guide on utilizing Moment.JS to determine if a timestamp falls within the range of two other timestamps

In my JSON array, specifically the 5th and 6th elements, I have the following data:

[   
{ 
    Day: 'Mon',
    EndTime: '{ts \'1970-01-01 18:00:00\'}',
    StartTime: '{ts \'1970-01-01 16:30:00\'}',
    courseName: 'Computer Science 250: Introduction to Website Design',
    Credits: '4' 
},  
{   
    Day: 'Mon',
    EndTime: '{ts \'1970-01-01 18:30:00\'}',
    StartTime: '{ts \'1970-01-01 17:30:00\'}',
    courseName: 'Math 220: Differential Equations',
    Credits: '3' 
}
]

The objects in the array are sorted based on the 'EndTime' values. I am encountering an issue when checking if the end time of the previous object (at i - 1 which is 18:00:00) falls between the start and end time of the next object (at i which ranges from 17:30:00 to 18:30:00), where instead of getting true from the isBetween method, it returns false.

I need help identifying and fixing the mistake in my code. Can you pinpoint what I'm doing wrong?

Below is the snippet of my code for reference:

for(let i = 1; i < monday.length-1; i++) {

const year = '1970-01-01';
const format = 'DD/MM/YYYY hh:mm:ss a';

  var next_endtime = monday[i].EndTime.substr(16, 8);
  var next_starttime = monday[i].StartTime.substr(16, 8);
  var prev_endtime = monday[i-1].EndTime.substr(16, 8);

  var plesson_e = moment(year + 'T' + prev_endtime, format), 
      nlesson_start = moment(year + 'T' + next_starttime, format), 
      nlesson_end = moment(year + 'T' + next_endtime, format);

  var testbool = moment(plesson_e).isBetween(nlesson_start, nlesson_end, 'time');

console.log(testbool);
}

Answer №1

The format you specified is not matching the string passed into moment:

const date = '1970-01-01'; // => notice the '-', and the year comes first
const givenFormat = 'DD/MM/YYYY hh:mm:ss a'; // => '/' used and day as priority

Consider updating the format to:

const correctedFormat = 'YYYY-MM-DD hh:mm:ss a';

View this fiddle

Answer №2

There seems to be an issue with the date and time format being passed to moment JS. Here is an example that works correctly:

const monday = [{
    Day: 'Mon',
    EndTime: '{ts \'1970-01-01 18:00:00\'}',
    StartTime: '{ts \'1970-01-01 16:30:00\'}',
    courseName: 'Computer Science 250: Introduction to Website Design',
    Credits: '4'
  },
  {
    Day: 'Mon',
    EndTime: '{ts \'1970-01-01 18:30:00\'}',
    StartTime: '{ts \'1970-01-01 17:30:00\'}',
    courseName: 'Math 220: Differential Equations',
    Credits: '3'
  }
]

const format = 'hh:mm:ss a';

var next_endtime = monday[1].EndTime.substr(16, 8);
var next_starttime = monday[1].StartTime.substr(16, 8);
var prev_endtime = monday[0].EndTime.substr(16, 8);

var plesson_e = moment(prev_endtime, format),
  nlesson_start = moment(next_starttime, format),
  nlesson_end = moment(next_endtime, format);

var testbool = moment(plesson_e).isBetween(nlesson_start, nlesson_end, 'time');

console.log(next_endtime, next_starttime, prev_endtime);
console.log(nlesson_end, nlesson_start, plesson_e);
console.log(testbool);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>

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

Steps for resetting a div's display after adjusting the device size

I have a code that displays horizontally on desktop screens and vertically on phones. It includes an x button (closebtn) that is only displayed on phones to close the menu bar. How can I automatically display it again after resizing the page back to deskto ...

Toggle the checkbox to either allow or prevent scrolling within the div element's content

I have successfully used jQuery to append content to a div on my website. In addition, I have applied CSS to the div with the following styling: #data { height: 700px; position: absolute; left: 0; right: 0; overflow-y: auto; vertical-align: b ...

I recently discovered how to modify the video source (src) within an html5 source tag, but I am encountering varied outcomes when using it within a function or with inline javascript

When attempting to change the src of a video tag using Javascript, I encountered an issue. The code works fine when placed inline, but as soon as I try to include it within a function or in the "onclick" event of a button tag, nothing happens. There are no ...

Executing a NestJs cron job at precise intervals three times each day: a guide

I am developing a notifications trigger method that needs to run three times per day at specific times. Although I have reviewed the documentation, I am struggling to understand the regex code and how to customize it according to my requirements! Current ...

Utilizing a hidden pointer to an array within the main function

I'm currently working with three files: Person.h, Person.cpp, and main.cpp. Within Person.h, I have defined all my classes, while the .cpp file contains the actual implementations. However, I've encountered a problem when attempting to iterate th ...

Invalid data type in Mongoose schema configuration

I am facing a situation where I have defined a schema similar to the following: analytics: { visits: { amounts: { type: Array, default: [] }, dates: { type: Array, default: [] } }, }, Howe ...

Unexpected Quote Will Not Appear

My random quote generator is not functioning properly, it should display a different quote on each click of the button. My colleagues are also facing the same issue. It was working fine when implemented in JavaScript, but after converting all the syntax to ...

Utilizing Base64 encoding and JSON for transferring high-resolution images

I have been utilizing this function to transmit an image to a server through JSON. To achieve this, I start by converting the image into NSData, then into NSString using Base64. The process works smoothly with smaller images, however, it crashes when attem ...

Troubleshooting: JQGrid not displaying records in ASP.net application connected to MySQL database

Can someone please assist me with my issue? This is my third post, and I am having trouble displaying records from my MySQL database. Any help would be greatly appreciated. Thank you in advance. ItemCode.aspx <script type="text/javascript"> ...

Incorporating a Searchable Dropdown with Bootstrap 4 in Google Apps Script

Recently, I attempted to incorporate a search feature using Bootstrap-select into my dropdown menu for Google Apps Script. Despite following this resource and including the necessary CDN and JS files from this location, I encountered difficulties implemen ...

What is preventing the bundling of my CSS into the application?

I'm facing an issue while setting up a new project using vue.js, scss, and webpack (with express.js on the server side and TypeScript). I copied over the configurations from a previous project where everything was working fine. According to my underst ...

Struggling with transferring a JavaScript array to the current page using AJAX

This might sound like a common question, but I have conducted thorough research and none of the solutions provided have worked for me. I have a javascript array structured as follows: [from: "2016-04-01", to: "2016-04-14"] I am sending this array via AJA ...

Using React's useEffect function with an empty dependency array to trigger a change in the

In the React application I'm currently working on, the useEffect function is triggered whenever the prop value changes from an empty array to another empty array. I am fetching query parameters from the page and passing them down to a component that ...

Can the new Clickatell API allow for the addition of a FROM field to SMS messages?

I have noticed that the new platform API on Clickatell does not seem to allow you to include a "from" field in the JSON payload. It gives an error stating it is not a two-way integration. However, there doesn't seem to be an option to add a text monik ...

Fade out the notification div using jQuery in MVC4

I'm a beginner in the world of JavaScript and JQuery and I could really use some assistance with resolving a simple issue that I've encountered. As part of my application's functionality, I am dynamically loading the following div based on ...

Exploring the versatility of the for each loop in Java when dealing with an array list containing multiple data types

Is it possible to use a for-each loop in Java with an array that contains multiple data types? Here is the code I currently have: ArrayList al=new ArrayList(); al.add("Ravi"); al.add("Vijay"); al.add("Ravi"); al.add("Ajay"); al.add(123); al.add(456); fo ...

Transferring large amounts of data to Parse.com in bulk

I am facing a challenge with importing approximately 10GB of data into Parse. The data is currently in JSON format, which makes it suitable for using the Parse importer tool. The issue I am encountering is that these objects do not have unique identifiers ...

Apache causes HTML download tag to malfunction

I have an HTML file that includes the following code: <a href="/Library/WebServer/Documents/file.zip" download="file.zip"> Download here </a> When I test this HTML page on Chrome, it successfully allows me to download the file. However, when ...

Is Swift affected by the same 2GB maximum serialization size issue as Java?

In programming languages like Java and other JVM based languages, it is common to serialize data into an array of bytes, especially when needing to send information over a network. But how does Swift handle data serialization for network communication? An ...

Creating a dynamic input box that appears when another input box is being filled

I have a form set up like this: <FORM method="post"> <TABLE> <TR> <TD>Username</TD> <TD><INPUT type="text" value="" name="username" title="Enter Username"/><TD> </TR> <TR> <TD>A ...