AngularJS - Increase the input date by 6 hours before converting it to JSON

Is there a way to add 6 hours to an input date in AngularJS?

I attempted the following code:

var eventStart = new Date ($scope.event.startdateid);
var startDate = new Date ( eventStart );
startDate.setHours ( eventStart.getHours() + 6 );

event.startdateid = new Date(startDate).toJSON();

However, nothing seems to be happening...

Here is my HTML snippet:

<input type="date" name="startdateid" ng-model="event.startdateid" min="{{date | date:'yyyy-MM-dd'}}">

Could you please point out where I may have made a mistake?

Thank you!

Answer №1

Don't worry about converting anything to JSON in the first place. Your code looks fine (though it's missing the use of $scope or controllerAsSyntax to pass variables to the view - let's assume it's just for demonstration purposes here), so any issues may be in your view.

To solve this, simply utilize the ngChange directive like so:

Check out this functional example:

var app = angular.module('app', []);

app.controller('mainCtrl', function($scope) {
  $scope.setHours = function() {
    $scope.event.startdateid.setHours($scope.event.startdateid.getHours() + 6);
  }
});
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="mainCtrl">
  <input type="date" name="startdateid" ng-model="event.startdateid" min="{{date | date:'yyyy-MM-dd'}}" ng-change="setHours()">
  <hr>
  <!-- The date with +6 hours -->
  <span ng-bind="event.startdateid | date:'yyyy-MM-dd HH:mm'"></span>
</body>

</html>

Answer №2

What about trying out momentJS library instead?

moment(someDate).add(6, 'hours');

Answer №3

If you're looking for a solution, I suggest utilizing the Datejs library

Here's one way to do it using vanilla JavaScript, without relying on any third-party libraries:

Date.prototype.addHours = function(h) {    
   this.setTime(this.getTime() + (h*60*60*1000)); 
   return this;   
}

Alternatively, you can simply adjust the time by 6 additional hours, similar to your existing code:

startDate.setTime(this.getTime() + (6*60*60*1000)); 

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

Ways to Randomly Flip Divs

I have developed an application where all divs flip vertically on hover. I am looking for a way to make the flipping random without requiring a hover. Any ideas on how to achieve this? .vertical.flip-container { position: relative; float: left; ma ...

Accordion featuring collapsible sections

Looking to build an accordion box using Javascript and CSS. The expanded section should have a clickable link that allows it to expand even further without any need for a vertical scroll bar. Any ideas on how this can be achieved? Thank you ...

How can data be passed from a directive to a controller in Angular?

I am currently working on implementing a directive pagination feature and I need to pass the current page number from the directive to a controller in order to run a specific function with this argument. However, I keep getting an 'undefined' err ...

Using Jquery selectors along with variables to perform targeted search operations

I need assistance creating a JQuery selector that can automatically add an active class to a specific list item based on a variable. The variable sv will hold either 'dom-site' or 'int-site', which correspond to the id of a list item i ...

Incorporating middleware in Next.js to remove route protection

Looking to remove the protection for the login page, and here is how my folder structure looks: https://i.stack.imgur.com/klPYV.png This is the middleware I am using: import { NextResponse, NextRequest } from "next/server"; export async functi ...

Can a form be submitted using an Ajax request triggered by a div element instead of an input type submit?

I used to submit the form by triggering $(".btn-update.").click() before, but now that I'm using $(".btn-update").ajaxForm(), the form is not getting submitted. Here is the HTML code: <form id="company-profile-edit-form" name="company-profile-edi ...

If a condition is present, the checkbox in the list needs to be unchecked

I have a query that relates to my previous question: Checkbox and ng-change. Need to uncheck if condition exists The previous solution worked for a single checkbox, but now I am dealing with a list of checkboxes: <tr ng-repeat="part in partstoorder"& ...

The 'npm start' command is failing to recognize the changes made to the

I am embarking on a new node application journey, starting with the package.json below, which is quite basic. { "name": "mynewnodeventure", "version": "1.0.1", "description": "Exploring node", "main": "index.js", "start": "node server. ...

Identify this concept: a data structure that arranges all elements in an array towards the beginning

Imagine a type of data structure that allows for random access, where removing one object causes all subsequent objects to shift forward. For instance, consider an array with a length of five but only containing three items: [A,B,C,null,null] If we remo ...

AngularJS can be used to set a specific character limit for text

I am struggling to get the limitTo filter working in my AngularJS application. Currently, I have a div that is supposed to display parsed HTML code like this: <div ng-bind-html="o.description | filter:unsafe | filter:limitTo:50"></div&g ...

Encountering an issue while attempting to locate an already existing product in the localStorage using JavaScript

I'm currently working on incorporating a cart system using localStorage and have provided the codes below. Can someone help me understand how to accomplish this? const data = { description: "Cum sociis natoque", mediaUrl: "/prod ...

The Mongoose .lt method is unable to process the post value

I came across this interesting Mongoose function snippet: exports.readSign = function(req, res) { if (req.user.roles.indexOf('admin') === 1) { Timesheet.find() .where('projectId').equals(req.params.projectId) ...

Guide to accessing URL or parameters in the directory of a NextJs 13 application

Transitioning my getserversideprops() to next13, I am faced with the task of incorporating URL and fetching parameters from the directory structure. In my page path /posts/{postId}, how can I retrieve params or the URL? The code snippet I am currently work ...

Harness the power of ng-click in conjunction with data-ng-href for a

I am attempting to create a button that takes the user to the product details while also having the ability to increase a counter using an ng-click function. <div class="row center-block save-button" > <a data-ng-href="/savings/{{saving._id}} ...

Executing both JavaScript Promise .then() and .catch concurrently

I've been working on converting my WordPress comments into an ajax-driven system. Everything was going smoothly until I encountered a problem with the .catch() method triggering right after the .then() method. Below is the code snippet... Ajax engi ...

Tips for handling function calls that result in RuntimeExceptions in Java?

I have to utilize tapestry-json as my JSON-API in Java: import org.apache.tapestry5.json.JSONObject; import org.apache.tapestry5.json.JSONArray; Unfortunately, there is no method called optJSONObject(int) to read JSONObjects from a JSONArray. Instead, th ...

dynamically loading jQuery scripts and content via ajax

I have a webpage that displays a file tree with links to different pages and subfolders. The folders are getting too large, so I want to use a jQuery script to hide them. However, the issue is that the tree is loaded dynamically through ajax, so the jQuery ...

How can I utilize Axios in Vue.js to access a local JSON file?

I'm trying to figure out how to read a local JSON file using Axios. The data.json file is located in public/info/data.json. However, every time I attempt to make a get request, I receive a 404 error message. Here is the content of data.json: [ {" ...

How to update an Array<Object> State in ReactJS without causing mutation

In my program, I store an array of objects containing meta information. This is the format for each object. this.state.slotData [{ availability: boolean, id: number, car: { RegistrationNumber : string, ...

What is the best way to identify a specific list item from a dropdown menu and determine its position on

Check out my jsfiddle for reference. My goal is to calculate scores based on different options selected, specifically relating to radiation types. I'm struggling with assigning a score to each type of radiation and integrating the drop-down menu selec ...