AngularJs从人类可读日期获取时间戳

时间:2013-12-19 09:37:46

标签: angularjs angularjs-directive

在角度JS中是否有办法从表单获取的日期中获取时间戳?

<label for="start">From:</label>
<input type="date" ng-model="startDate" />

我需要在指令中编写什么来转换这些数据?我没有找到关于这个特定问题的任何信息, 此致

3 个答案:

答案 0 :(得分:9)

由于您使用输入类型作为日期,因此模型中的字符串应与javascript中的Date对象兼容。所以你可以做到

var timestamp = new Date($scope.startDate).getTime()

答案 1 :(得分:8)

使用指令将值从视图更改为模型。

http://jsfiddle.net/bateast/Q6py9/1/

angular.module('app', [])
    .directive('stringToTimestamp', function() {
        return {
            require: 'ngModel',
            link: function(scope, ele, attr, ngModel) {
                // view to model
                ngModel.$parsers.push(function(value) {
                    return Date.parse(value);
                });
            }
        }
    });

答案 2 :(得分:2)

要在控制器中使用,您可以执行以下操作:

myApp.controller('TimestampCtrl', ['$scope', function($scope) {
  $scope.toTimestamp = function(date) {
    var dateSplitted = date.split('-'); // date must be in DD-MM-YYYY format
    var formattedDate = dateSplitted[1]+'/'+dateSplitted[0]+'/'+dateSplitted[2];
    return new Date(formattedDate).getTime();
  };
}]);

可以像这样使用:

<div ng-controller="TimestampCtrl">
  The timestamp of <input ng-model="date"> is {{ toTimestamp(date) }}
</div>