Arpit Meena Arpit Meena - 1 month ago 10
AngularJS Question

ui bootstrap datepicker not taking js Date() object as string

I am using ui bootstrap datepicker in my project, when i am getting data from database the type of this date value

Thu Aug 11 2016 00:00:00 GMT+0530 (India Standard Time)
when i am using

new Date('Thu Aug 11 2016 00:00:00 GMT+0530 (India Standard Time)');

Then it is working properly, i don't want to convert it in
new Date();
, i actually want to achieve this conversion using
how can i achieve this? my datepicker field is:

<input type="text" class="form-control custom-form-control" uib-datepicker-popup="{{format}}" ng-model="moduleName.main.expiryDate" is-open="expiryDateCal.opened" datepicker-options="expiryDateOptions" name="expiryDate" ng-required="true" close-text="Close"/>


Using filter is not a good idea in the case of with ng-model.So instead I've created a directive which converts the string date to Date object.

Run the code sample to check the working.Hope this helps,you just need to add date attribute to the HTML tags with ng-model as required.

var app = angular.module('app',[]);
  $"Thu Aug 11 2016 00:00:00 GMT+0530 (India Standard Time)";

app.directive('date', function(dateFilter) {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModelController) {
      ngModelController.$parsers.push(function(data) {
        //convert data from view format to model format
        return new Date(data); //converted

      ngModelController.$formatters.push(function(data) {
        //convert data from model format to view format
        return new Date(data); //converted
<script src=""></script>
<div ng-app="app" class="widget-content" ng-controller="Ctrl">

  <input type="text" ng-model="date" date/>