AngularJS and MomentJS – Formatting UTC to local time using a custom filter

Frequently in our app, we need to show date/time’s which are stored in our database as UTC time.  From a users perspective however, it is best to view datetime’s in their local timezones.

MomentJS is a great library that is used pretty heavily to display date/time’s in JavaScript in a friendly manner.  Combining MomentJS with AngularJS (and with a small custom filter).

We use “angular-moment” which provides Moment.JS directives for Angular.JS (timeago and more).

https://github.com/urish/angular-moment

We also like to have some conformity for formatting date/times throughout our app. Centralizing the formatting allows use to easily change the style/layout/format of our date/time’s and have that change occur throughout our entire app!

Once you have “angular-moment” running in your AngularJS app, add the custom filter to your AngularJS app.

Our custom filter: (where “angularJSApp” is the name of your AngularJS app)

var angularJSApp = angular.module('angularJSApp', ['angularMoment']);

angularJSApp.filter('UTCToNow', ['moment', function (moment) {
     return function (input, format) {
            if(format)
            {
                return moment.utc(input).local().format('dddd, MMMM Do YYYY, h:mm:ss a');
            }
            else
            {
                return moment.utc(input).local();
            }
        };
    }]
);

How to use the custom filter in our HTML:

{{dateCreated | UTCToNow: true }}
<br />
<span am-time-ago="dateCreated | UTCToNow"></span>

You should now see your date/time in your local timezone

Advertisements

One thought on “AngularJS and MomentJS – Formatting UTC to local time using a custom filter

  1. Tom Needham says:

    Cheers for this little tip!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: