【问题标题】:Format input field "time" to not show seconds and milliseconds将输入字段“时间”格式化为不显示秒和毫秒
【发布时间】:2016-12-05 09:42:29
【问题描述】:

在 AngularJS 1.5 中,我有一个带有“时间”类型的输入字段的表单。它可以工作,但显示的时间应该是 HH:mm - 没有秒等。

Chrome 默认执行此操作,但 Firefox 和 Internet Explorer 以秒和毫秒显示(例如,“14:56:00.000”而不是“14:56”)。

如何在所有浏览器中显示所需的时间格式?

<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-time-input-directive-production</title>
  
  <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
    
</head>
<body ng-app="timeExample">
  <script>
 angular.module('timeExample', [])
   .controller('DateController', ['$scope', function($scope) {
     $scope.example = {
       value: new Date(1970, 0, 1, 14, 56)
     };
   }]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
   <label for="exampleInput">Pick a time between 8am and 5pm:</label>
   <input type="time" id="exampleInput" name="input" ng-model="example.value"
       placeholder="HH:mm" min="08:00" max="17:00" required />
   <div role="alert">
     <span class="error" ng-show="myForm.input.$error.required">
         Required!</span>
     <span class="error" ng-show="myForm.input.$error.time">
         Not a valid date!</span>
   </div>
   <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
   <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
   <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
   <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
   <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</body>
</html>

谢谢!

【问题讨论】:

  • 你是对的。但我的意思是输入字段中的日期格式,而不是文本字段中的日期格式。很抱歉造成误解。
  • 添加了一些可能有用的链接

标签: html angularjs


【解决方案1】:

Firefox 和 IE 不支持&lt;input type="time"&gt;,它取决于浏览器。有关 W3 的更多信息,请参阅this 链接。因此,您的输入字段将无法像在 Chrome 中那样显示。

另一种方法是使用uib-timepickerfrom angular-ui 或尝试使用jquery 中的一个,例如webshim

【讨论】:

    【解决方案2】:

    尝试使用 step 属性并将其设置为 60"。

    <input type="time" id="exampleInput" name="input" ng-model="example.value"
       placeholder="HH:mm" min="08:00" max="17:00" required step="60" />
    

    【讨论】:

    • 似乎这仅在您填写表格时有效,但在您显示日期时无效。
    • 在更新任何记录期间填写表单并在表单中填充值时工作。
    【解决方案3】:

    IE11 和 Safari 不支持日期时间输入类型。但我们希望一切顺利,并定期访问此“can_i_use”链接,看看是否发生了变化。

    https://caniuse.com/#feat=input-datetime

    【讨论】:

      【解决方案4】:

      我们可以在控制器端写一个通用的方法,让输入类型time中不显示秒和毫秒

      getFormatDate = function (val) { // assuming val is date like "/Date(946673340000)/"
       if (val != undefined) {
          date = new Date(val.match(/\d+/)[0] * 1); // creating a date object from val
          return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 
        date.getHours(), date.getMinutes());
       }
      }
      

      【讨论】:

        猜你喜欢
        • 2021-10-11
        • 1970-01-01
        • 2014-01-09
        • 2020-09-04
        • 2011-09-26
        • 2013-03-17
        • 1970-01-01
        • 2010-12-22
        相关资源
        最近更新 更多