In this tutorial we will learn to display time relatively in our Angular applications.
Displaying relative time has become quite popular in past few year, with all the major social networking websites showing relative time for timelines.
For example instead of showing a static time stamp for time, we show it as “a min ago“, and this will dynamically update on regular intervals depending on the time passed.
To implement this feature we will use the “angular-moment” library. This library uses the awesome “moment.js” behind the scenes and provides us with handy directives and filters which we can use to display time relatively.
For the illustration I’ll be developing a quick demo app that will demonstrate the capabilities of this libraries.
To use angular-moment we need to first include the “moment.js” library and then “angular-moment.js” library.
Next we will define our angular module and then inject “angularMoment” as a dependency. We will also setup our controller.
In our controller we assign the vm.time variable a new date-time object.
In our view we will first declare our app and controller. We also display the plain time returned by new Date().
To display time relatively angular-moment provides us with am-time-ago directive. This directive takes the reference-time as an attribute and then displays relative time with respect to the reference-time provided. Add the below to your code to display time relatively.
This kind of formatting is mostly used when displaying timelines on social networks or any other places where the content is updated frequently.
amCalendar filter formats the date and displays the relative date, with respect to the reference date provided. This depends on how close the reference-time’s date is to the current date.
eg: Last Monday at 4:30 AM, Yesterday at 4:30 AM, Today at 4:30 AM etc.
The basic usage is as below.
This kind of formatting could be used to display dates for events, occasions gatherings.
There are more formatting or display options available with angular-moment, visit the Github page.
This is current time minus 2 hours!
Please wait a miniute and observe the below time dynamically updating.
We have organized an event and its happening right now.
Human brain interprets relative time faster than actual time stamp. Using this effect in our applications would make it a lot more easier to our users to relate the time of the post/event. Angular-Moment provides a cool set of directives and filters that helps us to implement this feature in our application with ease. So go ahead and try it in your Angular Projects.
There are a lot more other directives and filter provided by Angular-Moment that allows us to play with time. Read here.
class="post-template-default single single-post postid-696 single-format-image samba_theme samba_left_nav samba_left_align samba_responsive cookies-not-set wpb-js-composer js-comp-ver-5.0 vc_responsive"