Combining Date and Time input strings as a Date object
angularjs, datetime, javascript
Solution
In angular it would go something like this:
Controller:
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>
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.
Fidle
Problem
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. How do I achieve this when using AngularJS?