Hamburgersn Heroin Hamburgersn Heroin - 23 days ago 15
AngularJS Question

Moment JS Angular 2 - after 24 hours just show normal date

I am trying to put together a chat application and I have never dealt with momentjs before. Basically I want it to show that a comment was posted seconds ago, minutes ago, hours ago.. but then I need it to just show the date rather than 1 day ago, 2 days ago etc etc...

I am using angular2 to build the app (also quite new to it) and dealing with javascript date objects is kind of tricky.. has anyone ever done this before ? let alone with Angular2.. i have tried the following but something is off.. no errors but its just not calculating it correctly

@Pipe({
name: 'formatDate2'
})
export class DatePipe2 implements PipeTransform {
transform(value: any, args?: any): any {

let result:string;
// current time
let now = new Date().getTime();

// time since message was sent in seconds
let delta = ( now - value ) / 1000;
console.log(delta);
// format string
if (delta < 10) {
result = 'jetzt';
} else if (delta < 60) { // sent in last minute
result = 'vor ' + Math.floor(delta) + ' Sekunden';
} else if (delta < 3600)
{ // sent in last hour
result = 'vor ' + Math.floor(delta / 60) + ' Minuten';
} else if (delta < 86400) { // sent on last day
result = 'vor ' + Math.floor(delta / 3600) + ' Stunden';
} else { // sent more than one day ago
result = 'vor ' + Math.floor(delta / 86400) + ' Tagen';
}
return result;

}
}

Answer

As you've tagged this with momentjs, here's how you would do what you're after with momentjs. You can include a localized version of momentjs to display german messages instead.

var tenSecAgo = moment().subtract(10, "seconds");
var twoDayAgo = moment().subtract(2, "days");

function showSinceOrDate(date) {
  var now = moment();
  if (moment.duration(now.diff(date)).asHours() > 24) {
    return date.format("DD.MM.YYYY HH:mm");
  } else {
    return date.fromNow();
  }
}


console.log(showSinceOrDate(tenSecAgo));
console.log(showSinceOrDate(twoDayAgo));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment-with-locales.min.js"></script>

Also have a look at moment's documentation