Skip to main content

Conversion between Date String and Timestamp using Angularjs Directive

Let me ask you one question. Can a veiwValue and modelValue have same value into a different format? The answer is YES. Here we will see how it can be possible. We will see it through a simple example that converts date string (viewValue) into timestamp (modelValue). We will use a text box to enter a date string (dd/mm/yyyy) and convert it into timestamp that will be stored into model value. The trick is that we will use $parsers to convert the date string into the timestamp and $formatters to change the timestamp stored in modelValue to date string that will be shown on text input. Let's see the codes first:

HTML Code:

<h4>Date to Timestamp</h4>
<div class="form-group">
  <label for="date1" class="col-sm-3 control-label">Date1 VeiwValue:</label>
  <div class="col-sm-3">
    <input type="text" id="date1" class="form-control" name="date1" ng-model="obj.date1" placeholder="dd/mm/yyyy" date-conversion>
  </div>

  <label for="date11" class="col-sm-3 control-label">Date1 ModelValue:</label>
  <div class="col-sm-3">
   <label class="control-label">{{obj.date1}}</label>
  </div>
</div>
<h4>Timestamp to Date</h4>
<div class="form-group">
  <label for="date11" class="col-sm-3 control-label">Date2 ModelValue:</label>
  <div class="col-sm-3">
   <label class="control-label">{{obj.date2}}</label>
   </div>
  <label for="date2" class="col-sm-3 control-label">Date2 VeiwValue:</label>
  <div class="col-sm-3">
   <input type="text" id="date2" class="form-control" name="date2" ng-model="obj.date2" date-conversion>
 </div>
</div>
Javascript Code:

var app = angular.module('myApp',[]);

app.controller('myAppCtrl',['$scope',function($scope){
 $scope.obj = {};
 $scope.obj.date2 = 1512239400000; // Date : 03/12/2017
}]);

app.directive('dateConversion',['$filter',function($filter){
 return {
  require : 'ngModel',
  link : function(scope, iElement, iAttribute, ngModelController){

   function datetotimestamp(veiwvalue){
    var regEx =  /^(\d{2})([-|\/]{1})(\d{2})\2(\d{4})$/;
       var reg_arr = veiwvalue.match(regEx);
       var timestamp;
       if(reg_arr){
        timestamp = new Date(reg_arr[3] + '/' + reg_arr[1] + '/' + reg_arr[4]).getTime();
        if(timestamp){
         return timestamp;
        }
       }
    return "Invalid Date";
   }

   function timestamptodate(modelvalue){
    if(modelvalue){
     return $filter('date')(modelvalue,'dd/MM/yyyy');
    }
   }

   ngModelController.$parsers.push(datetotimestamp);
   ngModelController.$formatters.unshift(timestamptodate);
  }
 };
}]);
Working Example:


As the value changes in the input box, it's value will pass through the $parsers (view to model pipeline). We have defined a datetotimestamp() function and pushed it into the $parsers array. In the datetotimestamp() function, we have captured the date string and perform a check for the validity of the date string and convert it into the timestamp and return it for the $validators. After the validation, the converted value is stored in the ngModel expression.

Similarly, as the model value changed programmatically, it will go through the $formatters (model to view pipeline). Here we have defined a function timestamptodate() and unshifted into the $formatters array. In the timestamptodate() function, we will convert the modelValue and return the string format of the timestamp. This value will be updated on DOM.

Comments

Post a Comment

Popular posts from this blog

$parsers and $formatters in Angularjs

$parsers and $formatters are array of function defined on ngModelController . When there is change in values (view or model), the value is passed through the $parsers or $formatters pipeline to convert it according to the needs. $parsers (View to Model): $parsers is an array of function which executes when there is change in view  value ( $veiwValue ), usually via user input. $parsers cause the conversion of view value into the form desirable to assign in model value. The value is passed through each $parsers function and the return value of one function is passed to next function. Last return value is passed to $validators and after validation the value is assigned to model. These $parsers functions are called array order (i.e. index 0 to n). $parsers are not called when there is change in model value programmatically. $parsers function must return some value. If it not, causes parse error and model value is set to undefined . Let's see the simple ...

Automatic Slashing the Date Input using Angularjs

We define a directive that will automatically slash the input field as user typein the date. The directive have following capabiltiy: The directive will append slash '/' when input field has 2 or 5 characters. The input will accept only 10 characters (dd/mm/yyyy). Validity of date provide will not be checked. When the backspace is pressed it will remove the last two character if last character is slash. Otherwise it will remove last character from the input field. The input will not accept characters other than numbers (0 to 9). Let's jump into the code. We will use bootstrap for awesome look: HTML Code: <div class="container" ng-app="myApp" ng-controller="myAppCtrl"> <div class="row"> <div class="col-sm-8 col-sm-offset-2"> <form class="form-horizontal"> <h4 class="bg-primary">Auto Slashing Date using Angularjs Directive</h4> <div class=...

Dive into ngIf directive and ngShow directive with example

ngIf and ngShow directives are used very frequently in Angular apps. Here will the difference between these two through an example. Firstly, let's see the main difference between these two as in angular docs: ngIf differs from ngShow and ngHide in that ngIf completely removes and recreates the element in the DOM rather then changing its visibility via display css property. The main points are as follows: ngShow directive uses css display property to show and hide the element in DOM. It does't remove the element from the DOM. It just set class="ng-hide" to hide the element and removes the ng-hide class to show the element. ngIf directive remove and reinsert the element based on the expression provided in ng-if directive. The inserted element has the state which was initialized at the time of compilation. If we change any css property of the element or set any class, that css property and class will be lost if the ng-if expression becomes false and...