0

I am implementing the Angular-UI datepicker as a directive, and I am trying to get it to display today's date as the string 'Today' rather than 2015/04/27.

Is this possible? I could easily change $scope.dt to "Today" but then if I want to save that to my database, I'll need to convert it back, which is messy. It looks like a custom format....but I can't see from the code here how that would be done?

AncientSwordRage
  • 7,086
  • 19
  • 90
  • 173

1 Answers1

1

You can write a filter that would wrap original date filter provided by AngularJS and accept custom format, forwarding formatting to date if format is default or passed date is not today. Here is a sketch:

.filter('my_date', ['dateFilter', function (dateFilter) {
    function filter(date, format, timezone) {
        var today  = new Date();
        if (!(date instanceof Date)) {
            date = new Date(date);
        }

        if (format == "today") {
            if (date.getFullYear() == today.getFullYear() && date.getMonth() == today.getMonth() && date.getDate() == date.getDate()) {
                return "Today";
            } else {
                format = "yyyy/mm/dd"; // this is default
            }
        }

        return dateFilter(date, format, timezone);
    }
    return filter;
}])

To use:

{{dt | my_date:'today'}}

There is a room for improvements here: you can check out more dedicated procedure for converting to date whatever was passed into filter in AngularJS source (it accepts JSON in particular); default format can be parameterized.

NOTE. The outlined technique will work if you are ready to render input with date by yourself - i.e when you can select which filter to use. It will not work for ready-to-use datepicker-popup from AngularUI - it uses built-in date filter and there seems no way to override that except modifying sources of AngularUI. If popup is what you need you'll have to add "popup logic" by yourself

yozh
  • 1,213
  • 2
  • 10
  • 18