Working with filters is a great advantage of AngularJS. They change the information that you display to the users in a centralized way and make it easy to quickly change the formatting of things like numbers, strings and dates.
In this post I’ll show you how to filter the JSON date and what caveat I’ve found on implementing it.
When you’re working with a Microsoft product like their cloud based Azure services or Umbraco the JSON results return dates in a format that is common for them and that looks like:
[crayon-610a549970faa507672551/] Here, ticks represents milliseconds since epoch (UTC).
[crayon-610a549970fb4678889944/] This basically receives the string as the input parameter, the formatting value in the format parameter as another string. Then it checks if there is any input present and if it is large enough to be a JSON date string. Since those strings start with ‘/Date(‘ the string starting from the character on the 6th position will be taken and the remaining part will be parsed into an Integer using the parseInt function. This leaves the actual ticks value to be used as the Date timestamp. That value is then passed into the ‘date’ filter using the $filter(‘date’) call to pass the resulting input over to that one.
When using this filter for a string value somewhere in your html partial – with objects that have a JSON Date property called startDate like:
One caveat that I encountered using this filter approach was that when you use Angular’s date filter you have to take into consideration that it uses the browser’s localize settings to render the output per default. Since I live in The Netherlands and it has the timezone UTC/GMT +1. Every date from a JSON format would be given one hour since the local timezone settings from my browser would be applied. That is okay if you want to show an event date that is being viewed internationally but not if you simply want to render the exact time as retrieved from another source – it being a database or REST API.
In order to fix this you have to override the localization settings as it is the third (and optional) parameter of the date filter (the first being the date input, the second the format string and the third the localization offset). Like i’ve demonstrated below:
[crayon-610a549970fbb421653260/] When you specify the third parameter this way, the offset will be zero and the JSON date value will be extracted and formatted exactly as retrieved from the data source and finally filtered conform the formatting used by the date filter.