sachin
sachin

Reputation: 63

How to create datetime from date and time in AngularJs?

I am working on a project with AngularJs. Here I have 3 html controls.

below is html code.

<form>
  <div class="form-group row">
    <label for="" class="col-sm-2 col-form-label">Set date</label>
    <div class="col-sm-5">
      <!-- <input type="email" class="form-control" id="inputEmail3" placeholder="Email"> -->
      <datepicker date-format="yyyy-MM-dd" selector="form-control">
        <div class="input-group">
          <input class="form-control" placeholder="Choose a date" ng-model="date" id="date" />
          <spam class="input-group-addon" style="cursor: pointer">
            <i class="fa fa-lg fa-calendar"></i>
          </spam>
        </div>
      </datepicker>
    </div>
  </div>
  <div class="form-group row">
    <label for="" class="col-sm-2 col-form-label">Set time</label>
    <div class="col-sm-4">
      <input type="time" class="form-control" placeholder="From" ng-model="from" id="from">
    </div>
    <label for="" class="col-sm-1 col-form-label">To</label>
    <div class="col-sm-4">
      <input type="time" class="form-control" placeholder="To" ng-model="to" id="to">
    </div>
  </div>
</form>

now for service call i need to pass datetime, but here I'm having date and time separately.

How can I construct datetime from and datetime to from above available data?

Upvotes: 1

Views: 2666

Answers (1)

Matthew Cawley
Matthew Cawley

Reputation: 2818

You can combine the dates in a function in your controller. First format the dates/times using the Date.prototype.toISOString() method, then use the String.prototype.substring() method to take the datePart and the timePart separately, finally combine the two to create a new Date instance.

$scope.fromDate = getCombinedDateTime($scope.date, $scope.from);
$scope.toDate = getCombinedDateTime($scope.date, $scope.to);

function getCombinedDateTime(date, time){
  var datePart = date.toISOString().substring(0, 10);
  var timePart = time.toISOString().substring(10, 24);
  return new Date(datePart + timePart);
}

Upvotes: 2

Related Questions