Tips for altering date format in AngularJS version 1.x

Is there a way to transform the date format from 1-Jan-2018 to 1-1-2018 using angularjs?

One potential method is by utilizing HTML Template Binding as shown below:

{{ date_expression | date : format : timezone}}

Answer №1

var application = angular.module('application', []);

//application.directive('appDirective', function() {});
//application.factory('appService', function() {});

function ApplicationController($scope) {
  $scope.date_expression = '1-Jan-2018';
}

application.filter('DateFormatter',function(){
return function(dateInput, formatSpecifier) {
var currentDate= new Date(dateInput);
var addZeroDigit=function(integer){
if(integer<10){
return "0"+integer;
}
else{
return integer;
}
}
var month=addZeroDigit(currentDate.getMonth()+1);
formatSpecifier=formatSpecifier.replace("mm",month);
var day=addZeroDigit(currentDate.getDate());
formatSpecifier=formatSpecifier.replace("dd",day);
var year=currentDate.getFullYear();
formatSpecifier=formatSpecifier.replace("yyyy",year);
return formatSpecifier;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="application">
  <div ng-controller="ApplicationController">
    <span>
      {{ date_expression | DateFormatter:'dd-mm-yyyy'}}
    </span>
  </div>
</div>

Answer №2

If I understand correctly, this solution should be helpful for you

var app = angular.module('app', []);

//app.directive('appDirective', function() {});
//app.factory('appService', function() {});

function AppCtrl($scope) {
  $scope.date_expression = '1-Jan-2018';
}

app.filter('myFilter', function() {

  // In the return function, a single parameter must be passed in, which will be the data we work on.
  // We can also pass multiple other parameters into the filter optionally
  return function(input) {

    var output = input.split('-');
    var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    // Perform filtering here
    output[1] = monthNames.indexOf(output[1]) + 1;
    return output.join('-');

  }

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="AppCtrl">
    <span>
      {{ date_expression | myFilter}}
    </span>
  </div>
</div>

Answer №3

//Implement this custom filter 
app.filter('customDateFilter', function ($filter) {
   return function (input) {
       if (input == null) { return ""; }
       var formattedDate = $filter('date')(new Date(input), 'yyyy-MM-dd'); //Specify the desired date format here
       return formattedDate.toUpperCase();
   };
});

//HTML usage
<span>{{yourModelValueOfDate | customDateFilter}}</span>

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

Can you explain the distinction between a standard $.post() method sending strings versus one sending a file?

Curious as to why I am unable to upload a file through JQuery using the $.post() function? Are there any modifications that can be made to the request in order to enable file uploads? $.post(url, { file: fileName, path: "/uploaded_files" }, function (res ...

What is the best JavaScript framework for implementing client-side hyphenation?

Looking to improve my website's readability, I want to implement client-side hyphenation using JavaScript for longer texts. Although CSS3 hyphenation is preferred, it's not always available. So far, I've been using Hyphenator.js, which, whi ...

How to filter out content not contained within a specific form tag using Javascript

One feature of my webpage displays restaurant reviews, each with a like button. However, the issue arises when submitting the like form: everything within and outside of a particular form tag gets sent to the back-end. This makes it challenging to determin ...

Generate fresh JavaScript objects with customized properties

My goal is to use Javascript and JQuery to automatically create a new object with properties provided by the user when they fill out an HTML form. I have a constructor named "object" for this purpose. function object (prop1, prop2, prop3) { this.p ...

Using styled components but lacking the ability to use the className property

Currently, I am working with React and styled components and utilizing a third-party component called IntlTelInput. Below is a snippet of my code: const StyledIntlTelInput = styled(IntlTelInput)` background: blue; `; export default function PhoneNu ...

Utilize NodeJS API to convert a base64 data string into a downloadable PDF file

My NodeJS API is set up to communicate with another API and fetch a data object in the form of a Base64 string. The client making the API call needs to be able to download a PDF file generated from this base64 data. What is the best way to return the dat ...

When invoking a function, jQuery may return an empty value

I am currently tweaking my jQuery script to retrieve a specific value upon page refresh in order to capture the return value. Initially, I attempted the following: var email_number = ''; // check if page refreshed or reloaded if (performance.n ...

What is the process of retrieving a property value from a database using selected values from cascaded drop-down lists?

I am facing a challenge where I need to extract a property of an entity by passing the IDs of selected items from a cascaded dropdown list. The requirement is to update the price every time there is a change in either level 1 or level 2 of the cascading dr ...

issues with the handler not functioning properly in html and javascript

<form method="post" action="."> <label class="input-label">Enter Your First Name</label><input field="first_name" class="input-edit" maxlength="30" type="text" value="{{ user.first_name }}" /> <label class="i ...

JavaScript: Receiving an error that function is undefined when working with data binding

Why is my code showing that it's not defined while I'm attempting a simple code with data binding? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="ht ...

Enable Ace Editor's read-only mode

I'm having some difficulty getting my ace-editor to work in read-only mode. I'm working with Angular 9 and I've attempted the following approach: In my HTML file, I have the following code: <ace-editor mode="java" theme="m ...

Unable to update content within the `style` attribute when the HTML is stored in a variable

I am attempting to make changes to the style html - specifically by replacing a string, but unfortunately it is not functioning as expected. I am struggling to obtain the final updated html. Below is my attempt: var html = "<style>043BF83A8FB24A418 ...

Transferring files from the android_asset directory to the SD Card

I am trying to play video files that are packaged within a Cordova application. My goal is to transfer these files from the android_asset folder to the SD card using the File API in JavaScript. However, I am encountering difficulties in accessing this fol ...

What is the best way to define coordinates or set margins for the autoTable component in jsPdf when using React js?

While working with the jsPdf library to create a PDF in React, I am encountering an issue where I am unable to set margins for the autoTable when there are multiple tables on a single page. Below is the code snippet: import React from "react"; ...

What is the method for moving one div above or below another div using the scroll bar?

Here's the scenario I'm facing: I have rows with buttons that, when clicked, reveal a set of options. The challenge is that depending on where the row is located on the page, the settings need to open either above or below the button. When the b ...

Issue with bidirectional binding on angular material slide toggle not functioning as anticipated (Angular 4)

My angular material slide-toggle implementation seems to be working, but I'm facing an issue where it doesn't bind the value to the relevant variable as expected. // other irrelevant imports above.. import {MatDialog, MatDialogRef, MAT_DIALOG_DA ...

Dealing with multiple parameters within the app.param() function

Currently, I am developing an API using Express.js and facing a challenge in implementing an app.param() function for handling the id parameter in a GET request: app.param('id', (req, res, next, id) => { const envelopeIndex = Number(id); ...

"Printed within the custom directive, the ng model value shows up as undefined

I am currently in the process of creating a custom directive that involves a simple template consisting of an input type textarea. I am assigning the ng-model to ngmodel and creating a link function where I am trying to capture the value of ngmodel. Howeve ...

Unexpected Error with Background Position Variable

Hello, I am attempting to create an animated background effect that moves up and down using the .animate() and .hover() methods in jQuery. Within my DOM, there is a div with id="#menu" containing a UL list where each item has a background positioned at dif ...

Difficulty activating JavaScript function - unsure of proper implementation

I'm having trouble with calling a function instead of an alert in my code. I tried using FunctionsName(); and removing the alert(''); but it doesn't seem to be working for me :( Could someone please take a look at the following code an ...