如何从angularjs输入时间获取小时和分钟

时间:2018-09-12 10:36:31

标签: html angularjs html5 datetime

我知道我必须使用<input type="time".....>来让用户输入时间。但是我非常需要知道如何分别使用小时和分钟的值来进行进一步处理。我到处都可以找到有关如何整体接受和打印时间的示例(例如object.value)。但是我目前需要专门为手头的任务提取小时和分钟。这是迄今为止我发现的唯一代码类型。

<!doctype html>
<html lang="en">
<head>
  <title>AngularJS Directives : input[time]</title>
   <script src="angular.js"></script>
   <style>
      b{font-family:Papyrus; color:#fa4b2a; font-size: 20px;} 
  </style>
</head>
<body ng-app="timeDemo">
  <script>
 angular.module('timeDemo', [])
   .controller('timeController', ['$scope', function($scope) {
     $scope.sample = {
       value: new Date(1999, 0, 1, 15, 30, 0)
     };
   }]);
</script>
<form name="demoForm" ng-controller="timeController as timeCtrl">
   <label for="sampleInput">Select a time from 6 am to 6 pm</label>
   <input type="time" id="sampleInput" name="input" ng-model="sample.value"
       placeholder="HH:mm:ss" min="06:00:00" max="18:00:00" required />
  <!-- min 6 am and max 6 pm i.e 18:00 -->
   <div role="alert">
     <span class="error" ng-show="demoForm.input.$error.required">
        Input is Required!</span>
     <!-- Required Error  -->
     <span class="error" ng-show="demoForm.input.$error.time">
       Input Date is  not Valid!</span>
    <!-- Validation Error -->

   </div>
  <i>value = <b>{{sample.value | date: "HH:mm:ss"}}</b></i><br/>
  <i>demoForm.input.$valid = <b>{{demoForm.input.$valid}}</b></i><br/>
  <i>demoForm.input.$error = <b>{{demoForm.input.$error}}</b></i><br/>
  <i>demoForm.$valid = <b>{{demoForm.$valid}}</b></i><br/>
  <i>demoForm.$error.required = <b>{{!!demoForm.$error.required}}</b></i><br/>
</form>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

Date对象应返回您要寻找的内容... 只需根据您的输入创建一个新的Date对象并使用该对象的方法。例如:

var d = new Date(sample.value);
var hours = d.getHours();
var minutes = d.getMinutes()

有关更多详细信息,请参见https://www.w3schools.com/jsref/jsref_obj_date.asp

相关问题