Tutorial

Display Time Relatively in Angular

Draft updated on Invalid Date
author

Chris on Code

Display Time Relatively in Angular

This tutorial is out of date and no longer maintained.

Warning: Moment.js is no longer actively maintained. And ngx-moment has replaced angular-moment.

Introduction

Displaying time relatively has become popular in the past few years. This can be seen across social networks like Twitter and Facebook.

For example, instead of displaying the time of a post like 8:12am, the time will be displayed as 3 hrs.

This helps our users see time relatively and makes it easier to think about how long ago an update was. We’ll be looking at how we can achieve this effect in Angular.

The Package

While Angular already comes with some great filters to help us deal with displaying times and dates, it doesn’t come with a way to display time relatively out of the box.

The package that will help us display time relatively is angular-moment. This package uses the awesome Moment.js library. If you haven’t used Moment before, definitely give it a look through; it can help with all sorts of scenarios where you have to work with date and time in JavaScript.

Related Reading: All About the Built-In AngularJS Filters: Date and Time

Installing

There are a few ways to install this package. For this tutorial, we’ll just be grabbing from a CDNJS.

All we have to do is add the following lines to our project:

    <!-- load momentJS (required for angular-moment) -->
    <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js"></script>

    <!-- load angular-moment -->
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular-moment/0.9.0/angular-moment.min.js"></script>

MomentJS is a requirement to use this package so that must be included in your project.

A Quick Angular App

Here’s a very quick Angular application to demonstrate the different ways this package can be used. All we need to show off relative times is an Angular module, Angular controller, and a variable for the time.

We’ll be working inside a CodePen for this. If you’d like to follow along, go ahead and create your own CodePen. When working in CodePen, make sure that you load your assets through the JS settings.

Make sure that Angular is selected and that you link to the two resources needed: moment and angular-moment.

Angular Module

Here is the code for the Angular side of things. Place this in the JS tab.

    // create an angular app
    angular.module('timeApp', ['angularMoment'])

    // create an angular controller
    .controller('mainController', function() {

      // bind the controller to vm (view-model)
      var vm = this;

      // create a new time variable with the current date
      vm.time = new Date();

    });

We have created a new time here using new Date(). You can also pass in your date/time into Date() to convert it to a date object. With our data and Angular application ready, let’s move onto the HTML tab to see how we can display this vm.time variable to our users.

The Views

We have to apply our Angular module (timeApp) and our Angular controller (mainController) to our application, so let’s start our view with:

    <!-- apply our app and controller -->
    <div class="container" ng-app="timeApp" ng-controller="mainController as main">

      <div class="jumbotron">
        <p>The time is {{ main.time }}</p>
      </div>

      <!-- show our relative times here -->

    </div>

At the very top of our document, we are going to show the time to see what we are starting with. At the time of this writing, I see:

The time is “2015-02-04T05:49:33.190Z”

The main ways that we can use this package are as a directive and as a filter. Let’s demonstrate both ways.

The Methods of Using this Package

Relative Time - Directive

Here is the bare minimum we need to use angular-moment as a directive.

    <time am-time-ago="main.time"></time>

The am-time-ago will automatically update the time. When you first see it, you will see a few seconds ago. If you wait a little longer, you’ll see 3 minutes ago.

In addition to using the directive, we also have the ability to use a filter when displaying time.

Date Format - Filter

When using a filter, you can declare the exact format that you’d like to see:

    <time>{{ main.time | amDateFormat: 'dddd, MMMM Do YYYY, h:mm a' }}</time>

The above would display: Tuesday, February 3rd 2015, 9:49 pm

You can pass in any format you like to get the date exactly how you’d like it. That looks a lot better than the 2015-02-04T05:49:33.190Z that we started out with.

Calendar Format - Filter

The third way that you can use the angular-moment package is the calendar format. Moment comes with calendar time which is a little different than the time ago example from earlier.

The calendar format will show different strings based on how close the time is to a certain time (usually now). What this means is that if a date/time was yesterday, you will see Yesterday 9:49pm. If you had a time from a week ago, the calendar time would display Last Monday 9:49pm. If the time has gone beyond a week, then you will just see the normal date (7/10/2011).

    <time>{{ main.time | amCalendar }}</time>

The above code would display: Today at 9:49 PM.

Best Practices

When using relative time, it’s important to still provide the exact time information to your users. If you look at Twitter, it can be confusing since there are so many updates happening in real-time. You could see people having a conversation and each update could say 1 min ago. You would have no idea who said what when!

A good practice when using relative time is to define a title on your <time> tags so that a user has the ability to hover and see the exact time.

For example, we can use the angular-moment filter method to add a title:

    <time title="{{ main.time | amDateFormat: 'dddd, MMMM Do YYYY, h:mm a' }}">{{ main.time | amCalendar }}</time>

Now when you hover over this time, you will be able to see the time.

Conclusion

Hopefully, this simple but powerful package will help you when displaying times to your users. This is a friendly way to provide more context to your users as they browse your application or your site.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Chris on Code

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.