将Date和Time输入字符串合并为Date对象 [英] Combining Date and Time input strings as a Date object
问题描述
我有两个输入标签,用于从用户选择日期和时间。
I have two input tags for picking date and time from user.
<p>Start Date</p><p> <input ng-model="sdate" type="date" ></p>
<p>Start Time</p><p> <input ng-model="stime" type="time" ></p>
这两个值传递给一个函数,我想将这两个输入值作为日期
对象:
These two values are passed to a function where I want to combine these two input values as a Date
object:
new Date(y, m, d, hh, mm, a)
然后我可以使用它来在日历中绘制事件的详细信息。如何组合这两个值?我试过:
Which I can then use to plot an event's details in a Calendar. How can I combine these two values? I have tried:
start:new Date(sdate + stime)
start:new Date(sdate , stime)
start: new Date(sdate.getFullYear() + sdate.getMonth() + sdate.getDate() + stime.getHours + stime.getMinutes())
但我没有尝试过的工作。
But none of what I have tried is working.
使用AngularJS时如何实现?
How do I achieve this when using AngularJS?
推荐答案
在角度上会如下所示:
In angular it would go something like this:
控制器:
function exampleController($scope) {
$scope.title = "$Watch sample";
$scope.$watch('sdate', function() {
tryCombineDateTime();
});
$scope.$watch('stime', function() {
tryCombineDateTime();
});
function tryCombineDateTime() {
if($scope.sdate && $scope.stime) {
var dateParts = $scope.sdate.split('-');
var timeParts = $scope.stime.split(':');
if(dateParts && timeParts) {
dateParts[1] -= 1;
$scope.fullDate = new Date(Date.UTC.apply(undefined,dateParts.concat(timeParts))).toISOString();
}
}
}
}
HTML
<div ng-app ng-controller="exampleController">
<h2>{{title}}</h2>
<p>Start Date</p><p> <input ng-model="sdate" type="date" ></p>
<p>Start Time</p><p> <input ng-model="stime" type="time" ></p>
{{fullDate}}
</div>
当您更改变量时,您需要使用$ watch listener对变量进行调用,然后调用函数。
You need to make use of the $watch listener on a variable when it changes, then call your function.
注意:如果您为此作出指示,会更好。
Note: it would be even better if you make a directive for this.
这篇关于将Date和Time输入字符串合并为Date对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!