What is the best way to showcase the times that fall within the designated start and end

Supposedly, I have a start and end time.

Here is an example:

var startTime = '12:30 PM';
var endTime = '03:00 AM';

Now, I need to show the time between that range with a 5-minute interval, add 3 hours to the start time and subtract 1 hour from the end time. The result based on the given time range will be:

03:30 PM
03:35 PM
03:40 PM
03:45 PM
03:50 PM
03:55 PM
04:00 PM
04:05 PM
....
....
02:00 AM

The first time displayed will be 03:30 PM because 12:30 PM + 3 hours = 03:30 PM

And the last time displayed will be 02:00 AM because 03:00 AM - 1 hour = 02:00 AM

I am using moment.js. Here is my code:

var startTime = '12:30 PM';
var endTime = '03:00 AM';

var startTime2 = '12:30 PM';
var endTime2 = '05:00 PM';

console.log(intervals(startTime, endTime));      // this is not working
console.log(intervals(startTime2, endTime2));    // this is working

function intervals(start, end) {
  var start = moment(start, 'hh:mm a').add(3, 'h');
  var end = moment(end, 'hh:mm a').subtract(1, 'h');

  var result = [];
  var current = moment(start);
  while (current <= end) {
    result.push(current.format('hh:mm a'));
    current.add(5, 'minutes');
  }
  return result;
}

My problem is that the given time

var startTime = '12:30 PM';
var endTime = '03:00 AM';

does not work. It only works if the given time is

var startTime2 = '12:30 PM';
var endTime2 = '05:00 PM';

I believe the issue lies in the PM-AM periods. How can we resolve this? Your help would be appreciated.

Answer №1

Here is a special condition you need to consider:

  if(end < start)
    end = end.add(1, 'd');

Feel free to review the entire code provided below:

var eventStartTime = '12:30 PM';
var eventEndTime = '03:00 AM';

var eventStartTime2 = '12:30 PM';
var eventEndTime2 = '05:00 PM';

console.log(calculateIntervals(eventStartTime, eventEndTime));      // this test case needs further attention
console.log(calculateIntervals(eventStartTime2, eventEndTime2));    // this test case is successful

function calculateIntervals(start, end) {
  var newStart = moment(start, 'hh:mm a').add(3, 'h');
  var newEnd = moment(end, 'hh:mm a').subtract(1, 'h');
  if(newEnd < newStart)
    newEnd = newEnd.add(1, 'd');
  var output = [];
  var currentMoment = moment(newStart);
  while (currentMoment <= newEnd) {
    output.push(currentMoment.format('hh:mm a'));
    currentMoment.add(5, 'minutes');
  }
  return output;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.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

My ExpressJS routes suddenly fail to function, leaving me unable to receive any responses

Currently, my old routes in express js are functioning properly except for one specific route. However, the new routes that I am creating are not working as expected - each time I make a request using Postman, I receive an error stating "couldn't get ...

Using TypeScript's reference function within an HTML document

It feels like ages since my early days of web development. Back when I first started coding, we would reference a script using a <script> tag: <html> <head> <script src="lealet.js"></script> <!-- I know the path isn´t c ...

"Creating the Perfect Parallax Effect: A Step-by-Step

Seeking to implement a responsive parallax effect on my website, I have the following structure: <section id="first"> <div class="text fixed" > <h1><b>aSs</b> lorem ipsum dolor sit amet</h1> <p> ...

Assign the value from JavaScript to the element with the "ng required" attribute, without resetting frm.$error.required to false

My situation involves using a button with ng-style that relies on frm.mybtn.$error.required as follows: ng-style="frm.mybtn.$error.required?{'border-color':'#a94442'}:''" I am updating the value of the button from JavaScript ...

When a specific condition is fulfilled, I must retrieve a random response from a designated array

I'm looking for a way to create a system where users can select multiple items and then generate a random answer from those selected options. Currently, I have a setup that requires manual input of options in a comma-separated format, but I want to st ...

"Resetting select fields in a Django application using jQuery: A step-by-step guide

Recently, I was tasked with taking over a partially-developed Django application. Python is familiar territory for me, but I am completely new to JavaScript. This application heavily relies on jQuery for various form manipulations. One specific issue I enc ...

Transmit the image produced by the frontend JavaScript

I recently acquired a third-party library that has the capability to generate screenshots. https://i.sstatic.net/dxEcb.png I am eager to store these screenshots on my server, and I am currently utilizing Axios. I believe it involves working with blobs, a ...

Having issues with clicking on a row in the table while using AJAX functionality

Experiencing a puzzling issue while attempting to add click functionality to table rows with AJAX, here is the JavaScript code used: //for tabs $(document).ready(function () { $("#tabs").tabs(); }); $(window).load(function() { jsf.ajax.addOnEven ...

Retrieve tag, custom taxonomy, and attachment information using the get_pages function

Currently, I have implemented code that retrieves all pages submitted by the currently logged-in author using the get_pages function. The retrieved result is then passed to Javascript via Ajax. Everything functions as expected, and the correct pages are be ...

Tips for resolving the error "Cannot access the title property of undefined" when utilizing NextJS prerendering

I am preparing this page in advance for a specific post within my Next.js application: import Head from 'next/head'; import Link from 'next/link'; import client from '../../lib/apollo/client' import POSTS_WITH_SLUGS from &apos ...

Refreshing the UI Grid in Angular

After triggering a modal pop up from another controller, upon closing the modal I need to perform an action and transfer the data to a separate controller that displays a UI grid bound to $scope.searchResultsGridOptions. In my ABCCtrl.js file: Upon modal ...

Having trouble looping through an array of objects containing images in Javascript?

I am currently facing challenges with iterating through an array of objects that contain images. The array appears empty when logged in the console, but upon inspecting it in the console, I can see all the objects along with their iteration numbers. I have ...

React - updates to server values do not display in DOM right away

When I work from the client side, I have a modal in my HomeComponent that allows me to select an element. My goal is to then display that selected element within the same HomeComponent (in the productosEnVenta function). The element chosen in the modal is ...

Utilizing PHP for Interactive JavaScript Modals

Encountering an issue with my JavaScript. The modal initially functions correctly, but upon clicking it for the second time, two modals appear - one from the previous click and another new one. The stacking of modals continues each time the button is cli ...

Unable to find the specified element within Gmail

Recently, I've been working on a project with Nightwatch.js where it checks the dev environment and sends a test email to a Gmail account. Following that, it logs into Gmail, locates and clicks on the correct email. My main challenge now is trying to ...

Struggling to fetch the JSON data for a specific field in NodeJS?

I am currently using NodeJS and MongoDB to make a GET request to an API endpoint. In my app.js file: app.get('/api/matches', (req, res) =>{ //console.log('Get matches..'); matches.find({}).then(eachOne => { res. ...

Sending external JavaScript code within an HTML file may result in incorrect server communication

I'm currently working on a setup where I have a Node.js server running alongside an Angular frontend. One of the dependencies in my Angular project requires me to import a javascript file called swing.js into my HTML page. However, when I attempt to d ...

The value stored in $_POST['valuename'] is not being retrieved

Having recently delved into ajax, I am encountering some difficulties in making it function properly. The objective of the code is to send two variables from JavaScript to PHP and then simply echo them back as a string. However, instead of receiving the e ...

Encountering an error with $mdDialog.alert

I am attempting to activate an Alert Dialog using Angular Material Design. Within my controller, I have: angular.module('KidHubApp') .controller('ActivityCtrl', ['$scope','$meteor', '$stateParams', &apo ...

Textboxes are being disabled upon the webpage loading

Initially, I have a hidden login form in one div that becomes visible when the "Login" button is clicked. This login form is located on the Master Page and includes client-side HTML5 validations for email addresses and passwords. In a child page with an A ...