Rob Watts
Rob Watts

Reputation: 7146

AngularJS show two dates without showing similar parts twice

How do I nicely display a date range consisting of two dates? The main thing I'm looking for is to not show something twice if it's the same for both dates. I'm thinking something like this:

Tue, 05 May 2015 19:31-20:31 GMT

Mon, 04 19:31 - Tue, 05 20:31 May 2015

It's okay if there is some overlap, for example:

Mon May 4th, 19:31 - Tue May 5th, 20:31 2015

The goal is to get something that is nice for users to look at. I don't know where to get started with this - for now I only know how to show both full dates. I haven't been able to find anything in my searching - plenty on how to format individual dates, but nothing to format two dates together.

I'm using AngularJS, but if you know how to do it without Angular, that would be fine.

Upvotes: 0

Views: 102

Answers (1)

Frank van Wijk
Frank van Wijk

Reputation: 3252

The tags in your question suggest you want to format a date range in AngularJS. However, this seems a general Javascript question to me, unless you are want so solve things elegantly using Angular filters.

I suggest you to use MomentJS which has a lot of utility functions for formatting and comparing dates. moment-range also could provide you some handy methods, however I don't see any formatting methods.

var date1 = momentjs('2015-05-05 12:15');
var date2 = momentjs('2015-05-10 12:15');

These date have overlapping years, months and times. You can detect this with date1.isSame(date2, 'year'). Do this with month, date, time, etc.

Then format your range with date1.format(...) + ' - ' + date2.format(...), depending on what date properties are the same.

Wrap all your code in an Angular filter if you want:

angular.module('myApp').filter('dateRange', function () {
  return function (date1, date2) {
    // date range stuff here
  };
});

Use the filter in your template after setting date1 and date2 on the $scope

{{date1 | dateRange:date2}}

Upvotes: 2

Related Questions