How to Localize dates in Angular
Many countries format dates and times in a different way. For example, between the US and UK, the order of months and days is often reversed in shortened dates. For example, 12/5/2017 is December 5th, 2017 (MM/DD/YYYY) in the US, while it would mean May 12th, 2017 (DD/MM/YYYY). Unlocalized date format can be potentially very confusing to your users and is an easy localization option offered by Angular's built-in Pipes helper.
How to do it...
Let's follow the steps to add date localization to our blog posts so that they will display in the format our readers would expect:
- We'll start by adding a simple date object to our
/src/app/posts/post/post.component.ts
component:
postDate = new Date();
- This will set the blog post date to the current time, which is good enough for this recipe. We can now use that date property in our template and pipe it into Angular's built-in date formatter:
<small class="pull-left">Posted - {{ postDate | date:'shortDate' }}</small...