Tips for utilizing Moment.js to display time in a 24-hour format while performing additions

In my application, I receive hours as strings such as "2230". I am looking for a way to add minutes to these hours in order to simulate the time after those minutes have been added. For example:

//"2230" + "60"mins = "23:30"
//"2230" + "180"mins = "02:30" 

I have read about Moment.js possibly offering a solution, but I'm struggling with:

  1. The correct method of formatting the hours initially using moment("2230").format()

  2. How to properly add minutes to it

  3. Making sure it follows a 24-hour clock when adding the minutes

Answer №1

Utilizing Moment can be incredibly helpful for this task. It may require some syntax manipulation, but here's a snippet that could achieve what you need:

moment("2230", "HH:mm")
  .add(60, "minutes")
  .format("HH:mm")

Don't hesitate to experiment with it on this platform: https://codesandbox.io/s/proud-pine-lz0fs?file=/src/index.js

By observing the code, you can see how Moment can parse the HH:mm format from a 4-character time string, enable you to perform operations like adding minutes, and then reformatting the output back into HH:mm.

For further guidance, here are two valuable resources:

https://flaviocopes.com/momentjs/

I trust this information proves beneficial to you!

Answer №2

To begin, you must first divide the given string in order to extract the hours and minutes.

const str = "2230"
const hours = str.substring(0, 2);
const minutes = str.substring(2, 4);

Once you have separated the hours and minutes, you can then pass them into a Moment object with ease.

const time = moment()
.set({"hour": hours, "minute": minutes})
.add(60, 'minutes')
.format("HH:mm");

The .set function is used to establish the specific time (hours and minutes).

Adding is done using .add to include the desired additional minutes.

Lastly, formatting is achieved through .format to customize the final output; Note that "HH" signifies a 24-hour clock, while "hh" denotes a 12-hour clock.

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

Performing an AJAX call every half-hour using JavaScript

I am looking to implement an ajax request every 30 minutes using JavaScript. Specifically, for the user currently logged in, I aim to retrieve any notifications that have a start date matching the current time. These notifications are set by the user with ...

Trigger a JavaScript function using PHP and retrieve the output

My goal is to execute a javascript function from a PHP script by passing a variable to the javascript function and then displaying only the response in the PHP script. I want to ensure that when a client views the source code of my php file, they can only ...

`Generate JSON list`

How can I properly encode an array in PHP as JSON, ensuring it includes two variables? $var = 33; $last = 44; Here are the database results: foreach($query->result() as $r) { $data[]= $r; // Fills the array with results } I am attempting to cre ...

An error occurred as the Serverless Function timed out while attempting to load a dynamic route in Next.js version 13

I have a basic Next.js application with the following route structure: /contentA/ - Static - Initial load: 103 kB /contentA/[paramA]/groups - SSG - Initial load: 120 kB /contentB/[paramA]/[paramB]/[paramC] - SSR (client component) - Initial load: 103 kB ...

What is the best way to change a String into an Array within MongoDB?

I need help with converting the type of an object that has been changed. Is there a way to transform this: { "_id" : NumberLong(257), "address" : "street Street, house 50, appartment 508, floor 5" } into this: { "_id" : NumberLong(257), "userAddres ...

AngularJS refrains from computing expressions

As a newcomer to AngularJS, I decided to experiment with some basic code. However, the results were not as expected. Here is the HTML code that I used: <!DOCTYPE html> <html ng-app> <head> <script src="js/angular.min.js"></sc ...

Ways to replace inline styles with print CSS?

While inline styles are often considered "evil", can they still be inserted into HTML using JavaScript (such as jQuery animation)? ...

What is the best way to start a jquery function within a tab that has been loaded using AJAX?

My AJAX loaded tabs are functioning correctly with the following code: <div id="tabs"> <ul> <li><a href="../about-leadership-admin-ajax/">Leadership / Admin</a></li> <li><a href="../about-sales-market ...

Mapping Form Fields (with Formik)

Currently, the Formik/Yup validation setup in my form is working perfectly: export default function AddUserPage() { const [firstName, setFirstName] = useState(""); const [email, setEmail] = useState(""); return ( <div> <Formik ...

Is it possible to dynamically pass a component to a generic component in React?

Currently using Angular2+ and in need of passing a content component to a generic modal component. Which Component Should Pass the Content Component? openModal() { // open the modal component const modalRef = this.modalService.open(NgbdModalCompo ...

Using Express.js, Passport.js, and SockJS to Link User Socket with deserializeUser

Recently, I have been working on a new project where I am utilizing Express 3, Passport.js, and SockJS. One of my requirements is to attach the user socket to the User instance so that I can use it in route handlers, such as for notifications. The code sni ...

Clever method for enabling image uploads upon image selection without needing to click an upload button using JQuery

Is there a way to automatically upload the file without having to click the upload button? Detail : The code below shows an input field for uploading an image, where you have to select the file and then click the "Upload" button to actually upload it: & ...

What is the process for updating or pushing state in NgRx?

Need help with updating the state after adding inputVal. Currently, it only works on the first click and throws this error: Error: TypeError: Cannot add property 1, object is not extensible import { createReducer, on } from '@ngrx/store' import ...

Is the uib-tooltip custom trigger malfunctioning?

One of the challenges I am currently facing involves implementing a tooltip on an input field. Here is my current implementation: <input id="test" uib-tooltip="my tootip" tooltip-trigger="customEvent" ng-model="test" /> I have been attempting to di ...

JavaScript: Transforming binary information from Uint8Array into a string causing file corruption

In my attempt to send a video file to a server in chunks using a basic jQuery $.ajax call, I followed these steps: Utilized the slice() method on the file object to extract a chunk Used FileReader.readAsArrayBuffer to read the generated blob Generated a ...

What is the process for manually assigning a value to a variable in a test within the Jest framework?

app.test.js In my jest file, I have the code snippet below: 'use strict'; const request = require('supertest'); const app = require('./app'); //https://stackoverflow.com/questions/1714786/query-string-encoding-of-a-javascrip ...

Tips for correctly loading all elements on an HTML page before making CSS modifications

This question has been asked several times in the past. I am asking because when I used the on ready callback in jQuery, it did not change the placeholder text of my element "search_input". $( document ).ready(function() { $("#search_input").attr(' ...

ts-jest should replace the character '@' with the '/src' folder in the map configuration

I have set up a node project using TypeScript and configured various paths in my tsconfig.json file, such as: "paths": { /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl' ...

Collection of clickable images that lead to creatively designed individual pages

Being relatively new to JavaScript and jQuery, my knowledge is solid when it comes to HTML & CSS. Currently, I have a page with 20 minimized pictures (with plans to increase to 500+ images) that open into a new page when clicked. Although I have no issues ...

Initiate an ajax request only when there are pre-existing ajax requests in the queue

Setting up the Form I've created a form that utilizes checkboxes to determine a selected number on a page: https://i.sstatic.net/BNQB0.png When a checkbox is selected, it triggers a call to a controller that saves the selection and returns the upda ...