Expanding angularjs date filter to support additional date formats

When working with Angularjs, you can utilize the Date Filter to format dates. Is there a way to get the date in the format outlined below?

dd(st || nd || th) mm yyyy
1st May 2014
1<sup>st</sup> May 2014

Should I develop a new custom filter for this specific format, or is it achievable to expand the date filter formats using $filterProvider? What approach would be most effective in this situation?

Answer №1

If you're looking to add ordinal filters to your project, you'll need a filter that can provide ordinals based on numbers. A useful filter that does just that can be found at https://github.com/chrisiconolly/angular-all-ordinal-filters (just a heads up, it's my own project).

To install this filter into your project, follow the instructions in the readme. In short, you can use the following commands:

bower install --save angular-all-ordinal

Then, include the script in your .html file like so:

<script src="path/to/angular-all-ordinal.min.js"></script>

Lastly, add the module as a dependency in your project:

angular.module('demo', ['ordinal'])

Once you've completed these steps, you can use the ordinal filter alongside the date filter by chaining them together:

<p>{{myDateObject | date:'dd'}}<sup>{{myDateObject | date:'dd' | ordinalOnly}}</sup> {{myDateObject | date :'MMMM yyyy'}}</p>

By combining these filters, you'll achieve the desired result:

<p>1<sup>st</sup> May 2015</p>

Answer №2

After encountering a similar need, I stumbled upon this page and decided to do some experimenting. Take a look at this:

Fiddle Example

var app = angular.module('app', []).filter('customFilter', function() {
  return function(input) {
    var date = new Date(input);
    var dayOfMonth = date.getDate();
    var suffix = dayOfMonth;
    var suffixes = ["th", "st", "nd", "rd"];
    var relevantDigits = (dayOfMonth < 30) ? dayOfMonth % 20 : dayOfMonth % 30;
    var suf = (relevantDigits <= 3) ? suffixes[relevantDigits] : suffixes[0];
    return  input+' '+suf;
  }
});

Answer №3

To achieve this, you can create a custom filter

filter('ordinal', function() {
  return function(input) {
    var suffix=["th","st","nd","rd"],
    value=input%100;
    return input+(suffix[(value-20)%10]||suffix[value]||suffix[0]);
  }
});

Take a look at the live example on http://jsfiddle.net/trinathm/vF2gt/

Answer №4

Indeed, it is possible to design your own unique filters, such as:

angular.module('', [])
  .filter('customFilter', function() {
    return function(input,param1) {
    ...

Utilizing this filter in your HTML is as simple as using any other filter, like {{somevalue | customFilter}}

When dealing with date-related issues, it's worth mentioning that you can also call filters directly from your code by injecting the $filter service. This way, you can extract various values from the filter, for instance:

 var filteredDate = $filter('date')(new Date(input), 'dd MMMM');

Combining all of the above, it seems like the most appropriate approach to implement the custom filter would be:

 angular.module('', [])
      .filter('customFilter', function($filter) {
        return function(input) {
            var filteredYearMonth = $filter('date')(new Date(input), 'MMMM yyyy');
            var filteredDay = (new Date(input)).getDay();
            var arr = ['st', 'nd', 'rd']
            var myDate = arr[filteredDay] || "th" + filteredYearMonth;

            return myDate
        ...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

angularjs bootstrap carousel not functioning as expected

HTML How do I apply an active class to the first image? I am trying to create a slideshow with images from a database but encountering issues. <div id="myCarousel" class="carousel slide" data-ride="carousel"> <div ...

Add hyphens to separate the words in AngularJS if there is a break in the string

Within a div of set width, a string is being bound to it. This string could be short or long. I would like for the string to break with a hyphen inserted on each line except for the last one. For example: If the string is "misconception" and it breaks at ...

The npm command returns an error message stating "Either an insufficient amount of arguments were provided or no matching entry was found."

I'm trying to pass a custom flag from an npm script to my webpack config, but I keep encountering the following error in the logs: Insufficient number of arguments or no entry found. Alternatively, run 'webpack(-cli) --help' for usage info. ...

Harness the power of the ioHook Node.js global native keyboard and mouse listener within your Browser environment

I'm dealing with a challenging issue that seems to have no solution due to security limitations. However, I'm reaching out to you as my last hope to find a workaround. For my project, I require a system that can monitor user mouse and keyboard a ...

The error message "TypeError XXX is not a function in NodeJS" indicates that

As I attempt to enhance the testability of my NodeJS API by incorporating a service, a peculiar issue arises. Specifically, upon injecting the service (class), an error is triggered stating that the method getTasks() does not exist. ROUTE const TodoServi ...

Shared items found in a pair of entities

This function currently returns the difference between two objects, but I need to modify it so that it returns the common objects instead. Any assistance on how to achieve this would be greatly appreciated. Array example: var array1 = [ { "Name": " ...

Move the div containing an <audio></audio> tag

Is it possible to drag a div with a width of 200px and an element into a droppable area, and once the div is dropped, have its size change according to the sound duration (e.g. 1px per second)? Check out this example on jsFiddle. Below is the code snipp ...

Node development does not operate continuously

I'm facing a minor issue with node-dev. I followed the instructions in the readme file and successfully installed it. However, when I run the command like so: node-dev somescript.js, it only runs once as if I used regular node without -dev. It doesn&a ...

retrieving the configuration settings from my customized service

When attempting to access my custom service within its config property in order to inject an HTTP interceptor, I am encountering the following issue: angular .module("common.services") .factory("redirectService", [" ...

Evaluating different attributes within a single entity

I was attempting to write some code that checks if two individuals share the same birthday. Person "a" and person "b" do not have the same birthday, yet the console output shows: a was born on day 1 a has the same birthday as a a has the same birthday as ...

Issues with CKEDITOR in Internet Explorer when multiple instances are used with different configuration files

My current challenge involves placing multiple CKEDITOR instances on a single page, each loading a different configuration file. While it functions correctly in Firefox (FF), Internet Explorer (IE) seems to apply the config file from the last instance on t ...

Learn how to mock asynchronous calls in JavaScript unit testing using Jest

I recently transitioned from Java to TypeScript and am trying to find the equivalent of java junit(Mockito) in TypeScript. In junit, we can define the behavior of dependencies and return responses based on test case demands. Is there a similar way to do t ...

Move the location of the mouse click to a different spot

I recently received an unusual request for the app I'm developing. The requirement is to trigger a mouse click event 50 pixels to the right of the current cursor position when the user clicks. Is there a way to achieve this? ...

What is the best way to retrieve the current quality label from JWPlayer using JavaScript?

My goal is to retrieve the Current Quality Label from JWPlayer 7 using JS, but instead of getting the defined labels like 360p, 480p, 720p, I'm only receiving numbers such as 1, 2, 3... This is what I've tried: playerInstance.getCurrentQuality( ...

Modify an HTML table and record any modifications as POST requests using Javascript

As a beginner in JavaScript and HTML, I am open to corrections if I am not following the correct practices. Recently, I delved into editing an HTML form table. {%extends 'base.html'%} {%block content%} <html> <body> <h4> Search ...

Javascript: recursive function fails to return existing value

I'm attempting to recursively loop through an array in search of a key that matches a specified regex pattern. Once the condition is met, the loop should halt and return the value of the key. The issue I am facing is that although the loop stops corr ...

Is there a way for me to retrieve the locator value of a webelement?

How can I retrieve the selector value used in a selenium webelement in javascript? Let's say I have the following object: var el = browser.driver.findElement(by.id('testEl')); I want to extract the text 'testEl' from this object ...

Gridsome server-side rendering encounters issues with Auth0 authentication when the window object is not defined

After successfully following the Auth0 Vuejs tutorial with Gridsome during development, I encountered a problem when trying to build using gridsome build. The build failed because window was undefined in a server context. I discovered some issues in the A ...

Modify session variable upon link click

Here is an extension of the question posed on Stack Overflow regarding creating a new page for different PHP ORDER BY statements: Create a new page for different php ORDER BY statement? The task at hand requires changing a session variable and refreshing ...

Dynamic jQuery slideshow featuring a variety of animations applied to individual elements

I'm interested in creating a custom jQuery slideshow that involves animating HTML elements within each slide differently. Specifically, I would like to have 3 divs sliding out to the left with delays on 2 of them, and then being replaced by equivalen ...