4

I am display last login time on my control panel. How do I display datetime like this:

1 hour ago, 
5 hours ago
codegrid
  • 977
  • 2
  • 13
  • 33
  • Here's some javascript based answers: 1) http://stackoverflow.com/questions/7641791/javascript-library-for-human-friendly-relative-date-formatting 2) http://stackoverflow.com/questions/6108819/javascript-timestamp-to-relative-time-eg-2-seconds-ago-one-week-ago-etc-best – David Spence Jul 08 '15 at 09:04
  • please attach your code – gkrupp Jul 08 '15 at 09:05
  • Take a look at [Moment.js](http://momentjs.com) – Wayne Ellery Jul 08 '15 at 09:06

3 Answers3

4

Moment.js is definitely a great way to do this. I've set up a Plunkr for you which shows a basic example on how you could do this.

http://plnkr.co/edit/64mfpDhUxdXcQo6r8Xrf?p=preview

To summarise, you can use the .fromNow() method to display the difference between your date and the current time:

$scope.difference = moment($scope.yourDate).fromNow();

If $scope.yourDate is from 1 hour ago, $scope.difference will be set to an hour ago.

EDIT

Based on your comment, I've update the Plunker to use the date you've provided.

$scope.yourDate = new Date('2015-07-08T14:02:42.973');
$scope.difference = moment($scope.yourDate).fromNow();

At the time of writing, this sets $scope.difference to 20 hours ago.

Andrew Sula
  • 939
  • 8
  • 24
0

You can use angular-timeago to achieve that.

Once installing the package, you will need to reference it in the angular.module as per the following.

var app = angular.module('ngApp', ['yaru22.angular-timeago']);

Then you can use inline pipes to cast any date value into "ago" string e.g.

{{myDate | timeAgo}}
helcode
  • 1,859
  • 1
  • 13
  • 32
0

To achieve this here is a simple package ngx-pretty-date that provides a simple date pipe.

Once you install the package just import it into your app.modules.ts

import { NgxPrettyDateModule } from 'ngx-pretty-date';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
    NgxPrettyDateModule
  ],
  bootstrap: [...]
})
export class AppModule { }

Then use it in your components

<span> {{dateObj | prettyDate}} </span>