AngularJs get Timestamp from a human readable date

后端 未结 3 1923
刺人心
刺人心 2021-01-13 20:53

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




        
相关标签:
3条回答
  • 2021-01-13 21:05

    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()

    0 讨论(0)
  • 2021-01-13 21:30

    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>
    
    0 讨论(0)
  • 2021-01-13 21:31

    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);
                    });
                }
            }
        });
    
    0 讨论(0)
提交回复
热议问题