简体   繁体   中英

Display the custom string (“Today”) on set date (date=today), in the Angular-UI-Bootstrap Datepicker?

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?

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 - ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM