jazzoria jazzoria - 23 days ago 8
AngularJS Question

split time between start time and end time for user given minutes as input

In my app I have a drop-down for booking an appointment with psychiatrist. Here the user gives the input as minutes, to talk to the doctor,so in drop-down it should look like a normal timings like 9-10 am, 10-11pm so on till 5pm, so the customer can see the available timing to book the appointment. I'm struggling to get this time split. I have done only the conversion from mins to hours and after that Im struck with the time split.Hoping for some help here, or any valid guidance for proceeding to get the time split.

Controller:

myApp.controller('ctrl', function ($scope) {
$scope.calc = function () {
var time = $scope.timeSelect;
if (time < 60) {
var a = (time) + 'm';
} else if (time % 60 == 0) {
var a = (time - time % 60) / 60 + 'h';
} else {
var a = ((time - time % 60) / 60 + 'h' + ' ' + time % 60 + 'm');
}
$scope.result =a;
}
$scope.result='';
});

Lex Lex
Answer

Whenever you are dealing with dates and times I highly recommend using Momentj.js. Here is an extremely contrived example to demonstrate how you might use Moment.js to set your time periods.

angular.module("app", ["angularMoment"])
  .controller("ctrl", function($scope, moment) {
    var startingTime = moment().hours(9).minutes(0);
    var endingTime = moment().hours(17).minutes(0);
    $scope.selectedTimeslot = "";
    $scope.intervals = [15, 30, 45, 60, 90, 120];
    $scope.interval = 60;
    $scope.timeslots = [];

    $scope.setTimeSlots = function() {
      $scope.timeslots = [];
      var currentStartTime = angular.copy(startingTime); // use copy to avoid reference issues since we're dealing with objects and not primitives
      while (currentStartTime < endingTime) {
        $scope.timeslots.push(currentStartTime.format("h:mm") + " - " + currentStartTime.add($scope.interval, "minute").format("h:mm"));
      }
    }

    $scope.setTimeSlots();

  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-moment/1.0.0/angular-moment.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  Interval in minutes: <select ng-model="interval" ng-change="setTimeSlots()" ng-options="i for i in intervals"></select>
  <br/>Timeslots:
  <select ng-model="selectedTimeslot" ng-options="slot for slot in timeslots">
    <option value="">Please select</option>
  </select><br/><br/>
  Selected timeslot: {{selectedTimeslot}}
</div>