The AngularJS library has a date filter that allows JavaScript Date objects to be displayed using a provided format. This is an awesome feature, and it's great that you can use it anywhere, including text input boxes. But the problem is that it only works one-way. There's currently no way to convert strings back into Date objects while using the same format initially used to display it. This parser was designed to overcome this problem.
This is a basic example demonstrating how the parser can convert manually entered date strings into JavaScript Date objects.
Selected date: {{date | date:'MMM d, y h:mm a'}}
<input type="text" ng-model="date" date-parser="dd.MM.yyyy HH:mm" />
The AngularJS date filter comes with several shortname formats that you can use. The DateParser can recognise these formats and will convert the date strings accordingly.
Selected date: {{date | date:'MMM d, y h:mm a'}}
<input type="text" ng-model="date" date-parser="medium" /> <input type="text" ng-model="date" date-parser="short" /> <input type="text" ng-model="date" date-parser="fullDate" /> <input type="text" ng-model="date" date-parser="longDate" /> <input type="text" ng-model="date" date-parser="mediumDate" /> <input type="text" ng-model="date" date-parser="shortDate" /> <input type="text" ng-model="date" date-parser="mediumTime" /> <input type="text" ng-model="date" date-parser="shortTime" />
Date string formats can be changed on-the-fly and associated views will automatically be updated to use the new format.
Selected date: {{date | date:'MMM d, y h:mm a'}}
<input type="text" ng-model="date" date-parser="{{format}}" />
The parser also allows you to change the timezone. However, bear in mind that the model will still contain the date and time for the local timezone, minus the offset.
Selected date: {{date | date:'MMM d, y h:mm a Z'}}
<input type="text" ng-model="date" date-parser="dd/MM/yyyy HH:mm Z" />
You can also use angular-dynamic-locale to dynamically switch the app locale.
Selected date: {{date | date:'MMM d, y h:mm a Z'}}
angular.module('demoApp', ['dateParser', 'tmh.dynamicLocale']) .config(function($dateParserProvider, tmhDynamicLocaleProvider) { $dateParserProvider.watchLocale(true); tmhDynamicLocaleProvider.localeLocationPattern('//cdnjs.cloudflare.com/ajax/libs/angular-i18n/1.4.9/angular-locale_{{locale}}.js'); }) .controller('controller', function($scope, tmhDynamicLocale){ $scope.format = 'dd.MM.yyyy'; $scope.date = new Date(); $scope.locale = 'en'; $scope.$watch('locale', function(value, oldValue) { if(value !== oldValue) { tmhDynamicLocale.set(value); } }); });