Using JavaScript to parse a time string and update it by adding minutes

$.getJSON("api/times", function(times) {
    var time1 = times.departure; // 14:36:30 (string)
    var minutesToAdd = parseInt(times.minutesToAdd); // 6
    var total = "?"; // How can I add minutesToAdd to time1?
});

I need to manipulate the time1 variable in order to add the value of minutesToAdd to it. The initial value of time1 is retrieved from a MySQL database and obtained through an API that provides the data in JSON format. What would be the best approach to achieve this?

Answer №1

Here's a helpful suggestion for you:

In order to work with dates and times in JavaScript, it's important to include a demo date along with the time. This will allow you to create a date object that can be manipulated as needed. By using the getTime() method, you can retrieve the time in milliseconds.

var newDateObj = new Date("01/01/13 14:36:30"); // '01/01/13' is just an example date
alert(newDateObj)
var date = new Date(newDateObj.getTime() + 5*60000);
alert(date) // Use date.getTime() to get the time value

Answer №2

If you prefer not to utilize Date, consider using the split function to extract the three components of your time string. Then proceed by adding the specified minutes while ensuring not to exceed 59 minutes (and also verifying that the hours do not go over 23 if deemed necessary):

$.getJSON("api/times", function(times) {
    var time1 = times.departure; // 14:36:30 (string)
    var minutesToAdd = parseInt(times.minutesToAdd);
    var time = time1.split(':');
    time[1] += minutesToAdd;
    if (time[1] >= 60) {
        time[1] = 0;
        time[0]++; // You may want to validate this against 24
    }
    var total = time.join(':'); // This is equivalent to "time[0]+':'+time[1]+':'+time[2]"
});`

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

Control the value dynamically with Powerange using JavaScript

I have incorporated the Powerange library into my form for creating iOS style range bars. This javascript library offers a variety of options provided by the author. Is there a method to programmatically move the slider to a specific value using JavaScrip ...

Access PHP variables in JavaScript

In my project, I have a file named english.php which holds various variable values stored in the $LANG array. For example: $LANG['value_1']="abc"; $LANG['value_2']="xyz"; In addition to numerous .php files that include require_once( ...

I am interested in creating an input range slider using React and TypeScript

This code was used to create a slider functionality import { mainModule } from 'process'; import React, { useState } from 'react'; import styled from 'styled-components'; const DragScaleBar = () => { const [value, setV ...

The thumbnail with the label "x640" is not found in the existing context, unable to retrieve it

public class Thumbnails { public string 640x640 { get; set; } public string 50x50 { get; set; } public string 320x320 { get; set; } public string 200x200 { get; set; } public string 120x120 { get; set; } public string 100x100 { get; ...

Prevent dragging functionality in ckeditor

Currently, I am encountering a problem with my ckeditor. The issue arises when I load a full page of HTML into the ckeditor. While it loads and displays correctly, I am seeking a way to restrict users from editing the alignment of the content, only allow ...

React and Redux encounter an issue where selecting a Select option only works on the second attempt, not the first

I am currently working on a React/Redux CRUD form that can be found here. ISSUE RESOLVED: I have encountered an issue where the state should be updated by Redux after making an API call instead of using this.setState. The concept is simple: when a user s ...

Issues with the ES version affecting back4app cloud code functions

Utilizing back4app as my backend service for deploying my React Native and JS app, I am currently experimenting with the 'Cloud Code Functions' feature. Being new to back4app, I encountered an issue when following their guide. I received this er ...

Unable to dynamically load images using webpack-image-loader and referenced in a JSON file

Currently, I am working on dynamically loading images from a JSON file using webpack-image-loader and React. Previously, I successfully used PNGs by placing the variable name in curly braces: import gratuita from 'images/gift-50.png'; <img ...

Utilize Perl to interpret the JSON response from the Vk.com API

When making an API request to vk.com ('wall.get'), the response is in JSON format. The modules I am using: use VK::App; use JSON qw(decode_json); use Data::Dumper; use JSON::XS; Full response: {"response":[1696,{"id":9298,"from_id":-95784908, ...

Issues detected between Angular and Express rendering operations

Having an issue with my angular code. It runs perfectly on its own, but when I try to access it on localhost with express, it only displays the HTML file. Here's my server code: var express = require('express'), app = express(); app ...

Unable to generate this QUIZ (JavaScript, HTML)

Hi there, I'm working on a sample quiz and having trouble displaying the result. As a coding newbie, I could really use some help. In this quiz, users answer questions and based on their responses, I want to display whether they are conservative, agg ...

Troubleshooting: Next.js - Issues with encodeURIComponent function when using `/` in getStaticPaths

Reproducible site showcasing the issue: Reproducible code example: https://github.com/saadq/nextjs-encoding-issue Homepage Food page The goal is to dynamically create static pages for different food items based on their titles. This functionality works ...

Instructions on creating a non-editable text area where only copying and pasting is allowed

I am looking to simply copy and paste content into a textarea without needing to make any edits within the field. <form action="save.php" method="post"> <h3>Text:</h3> <textarea name="text" rows="4" cols="50"></textarea ...

I'm having trouble getting my home.js to render in the outlet component

After using Material-UI to create navbar.js, I encountered an issue where the other component was not rendering in the <Outlet/> Component RootLayout.js import { Outlet } from "react-router-dom"; import NavBar from "../component/NavBa ...

Verify the existence of a value in a MySQL table before proceeding with the selection process in Laravel 5

Check out my pivot table project_group: +-----+----------+------------+----------+---------+ | ids | group_id | project_id | admin_id | user_id | +-----+----------+------------+----------+---------+ | 4 | 115 | 1 | 1 | [3,4,5] | | ...

Leveraging jq in Jenkins pipeline

Currently, in my scenario, I am executing a pipeline that utilizes the AWS CLI through the withAWS plugin. To extract the necessary data, I employ jq. The issue arises when the sh command returns the output as a String. What is the best method to convert t ...

What is the reason behind the absence of the C++ syntax for a string loop in javascript?

UPDATE: At first, I believed that the following syntax was not functioning due to a mistake in my code and the fact that I have not encountered it being utilized in Javascript before. My primary concern lies in why this particular syntax is not more preval ...

Updating form in react requires a double click

I'm facing an issue with the popup form in my note-taking project. The popup form displays when a user wants to edit a note, and it should already contain the contents of the selected note. While the form shows the correct contents, I've noticed ...

Error encountered in Angular JS: $parse:syntax Syntax Error detected

var app=angular.module('myapp',[]) app.controller('myctrl',Myfunction); function Myfunction($scope,$compile){ var self=this; $scope.text=s4(); $scope.adding=function(){ var divElement = angular.element($("#exampleId")); ...

Run JavaScript on every website when the page loads

After loading all or specific pages in the browser, I am looking to run JavaScript code (predefined code). Are there any browsers and plugins/components that allow me to achieve this? The manual method involves opening the console (e.g. firebug) and execu ...