Dimitrios Vythoulkas
Dimitrios Vythoulkas

Reputation: 621

Get a combined Date from ui.bootstrap date and time pickers

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.

Upvotes: 0

Views: 91

Answers (2)

aitnasser
aitnasser

Reputation: 1246

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

Upvotes: 1

Shankar Gurav
Shankar Gurav

Reputation: 1067

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();
      }
    }
  }

Upvotes: 1

Related Questions