If you want to create a filter in AngularJS that can customize the date format, you can wrap the original date
filter and handle the formatting based on certain conditions. Here's a basic outline of how you can achieve this:
.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"; // default format
}
}
return dateFilter(date, format, timezone);
}
return filter;
}])
To use this filter, you can simply do:
{{dt | my_date:'today'}}
There are potential improvements that can be made to this filter, such as handling different input formats and making the default format customizable.
NOTE: This technique is suitable if you have control over how dates are displayed in your application. If you are using AngularUI's datepicker-popup
, which uses the built-in date
filter, you may need to implement your own logic for date formatting.