0

I'm trying to combine the Datepicker and Timepicker directives to get the date from the first and the time from the second in a combined Date object. I came across some examples that are not using these directives like this one Combining Date and Time input strings as a Date object. However when I try to apply something similar to my case it's not working. Console returns "TypeError: $scope.dt.split is not a function". Above is the function I try to use which is called by $watch.

function tryCombineDateTime() {
    if ($scope.dt && $scope.mytime) {
        var dateParts = $scope.dt.split('-');
        var timeParts = $scope.mytime.split(':');
        if (dateParts && timeParts) {
            dateParts[1] -= 1;
            $scope.fullDate = new Date(Date.UTC.apply(undefined, dateParts.concat(timeParts))).toISOString();
        }
    }
}

Here is a plunker showing the problem. http://plnkr.co/edit/tnbE3LWQTTzLhLWXLCQB?p=preview

I would prefer a solution based on my Plunker as I don't want to install other components like DateTimePicker.

Community
  • 1
  • 1

2 Answers2

1

Date format has been changed, so exception is being thrown, Try this

  function tryCombineDateTime() {
    if ($scope.dt && $scope.mytime) {
      var date = $scope.dt.toString();
      var time = $scope.mytime.toString();
      var dateParts = date.split(' ');
      var timeParts = time.split(' ');
      if (dateParts && timeParts) {
        dateParts[4] = timeParts[4]
        $scope.fullDate = new Date(dateParts.join(' ')).toISOString();
      }
    }
  }
Shankar Gurav
  • 1,057
  • 9
  • 17
1

your tryCombineDateTime function sould be like this:

  function tryCombineDateTime() {
    if ($scope.dt && $scope.mytime) {
        $scope.fullDate =new Date($scope.dt.getFullYear(), $scope.dt.getMonth(), $scope.dt.getDate(),$scope.mytime.getHours(),$scope.mytime.getMinutes()).toISOString();
    }
  }

this a working demo forked from your plunker

aitnasser
  • 1,216
  • 1
  • 9
  • 23
  • Thanks for this clean solution. However I think there is an issue. Whenever I pick a time it's not getting transformed in UTC time. The same time you pick from the form the same exact time is printed as UTC. – Dimitrios Vythoulkas Feb 15 '16 at 15:06
  • I changed it to that and it worked $scope.fullDate =new Date($scope.dt.getFullYear(), $scope.dt.getMonth(), $scope.dt.getDate(),$scope.mytime.getHours(),$scope.mytime.getMinutes()).toISOString(); – Dimitrios Vythoulkas Feb 15 '16 at 15:10