简体   繁体   English

AngularJS-向JSON输入日期增加6个小时

[英]AngularJS - Add 6 hours to input date to JSON

I don't know how can I add 6 hours to input date in AngularJS. 我不知道如何在AngularJS中输入日期增加6个小时。

I've try this : 我已经试过了:

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

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

But nothing happen ... 但是什么也没发生...

This is my HTML : 这是我的HTML:

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

Can you tell me when I make mistake ? 当我犯错时,你能告诉我吗?

Thank you ! 谢谢 !

First you don't need to convert nothing to JSON and your code seems correct (disregarding the fact that you aren't using even the $scope or controllerAsSyntax to send your variables to view - I'll prefer to think it was just to put here in question -), maybe you may have made some mistakes in his view. 首先,您不需要将任何内容都转换为JSON并且您的代码看起来是正确的(不管您是否甚至都没有使用$ scopecontrollerAsSyntax来发送变量进行查看的事实- 我宁愿认为它只是将这里有问题 -),也许您可​​能在他看来犯了一些错误。

So you just need to use ngChange directive to achieve this. 因此,您只需要使用ngChange指令即可实现此目的。

Here is a snippet working: 这是一个片段工作:

 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> 

为什么不使用momentJS

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

I'd recommend using Datejs 我建议使用Datejs

One way by doing it in JavaScript pure , no third party lib: 纯JavaScript实现的 一种方法,没有第三方库:

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

Or just update the time for 6 more hours Like your code: 或者只是将时间再更新6小时,就像您的代码一样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM