AngularJs get Timestamp from a human readable date

情到浓时终转凉″ 提交于 2020-01-11 06:01:34

问题


Is there a way in angular JS to get Timestamp from a date obtained by a form?

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

What will I have to write in the directive to transform this data? I didn't find anything about this particular issue, Regards


回答1:


Use a directive to change the value from view to model.

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:


Since you are using input type as date, the string in model should be compatible with Date object in javascript. So you can do

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




回答3:


To use in a controller you can do something like this:

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();
  };
}]);

And can be used like this:

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


来源:https://stackoverflow.com/questions/20677970/angularjs-get-timestamp-from-a-human-readable-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!