AngularJs gets timestamp from readable person

Is there a way in angular JS to get the timestamp from a date retrieved from a form?

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

What do I need to write in a directive to convert this data? I did not find anything in this particular problem, Relationship

+4
source share
3 answers

Use the directive to change the value from the view to the 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);
                });
            }
        }
    });
+8
source

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

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

+9
source

For 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 as follows:

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

All Articles