How to Use moment in Angularjs?

To use Moment.js in an AngularJS application, follow these steps:

  1. Include Moment.js in your project:

Include the Moment.js library in your project. You can either download it from the official website (https://momentjs.com/) or use a CDN like the following:

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
  1. Create an AngularJS module and controller:

Create a new AngularJS module and controller for your application:

JS

angular.module('app', [])
  .controller('MainController', function($scope) {
    // Your controller logic here
  });
  1. Use Moment.js in your controller:

In your controller, you can now use Moment.js to format dates, perform calculations, and more. For example, let’s format a date using Moment.js:

JS

$scope.formatDate = function(date) {
  return moment(date).format('MMMM Do YYYY, h:mm:ss a');
};

$scope.currentDate = new Date();
$scope.formattedDate = $scope.formatDate($scope.currentDate);

In this example, we create a function called formatDate that takes a date and formats it using Moment.js. We then use this function to format the current date and store it in the formattedDate variable.

  1. Display the formatted date in your HTML:

Add an element to your HTML that displays the formatted date:

HTML

<!DOCTYPE html>
<html ng-app="app">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
    <script src="app.js"></script>
  </head>
  <body ng-controller="MainController">
    <p>Current date: {{formattedDate}}</p>
  </body>
</html>

Here’s the complete example:

index.html – Main HTML file:

HTML

<!DOCTYPE html>
<html ng-app="app">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
    <script src="app.js"></script>
  </head>
  <body ng-controller="MainController">
    <p>Current date: {{formattedDate}}</p>
  </body>
</html>

app.js – Main JavaScript file:

angular.module('app', [])
  .controller('MainController', function($scope) {
    $scope.formatDate = function(date) {
      return moment(date).format('MMMM Do YYYY, h:mm:ss a');
    };

    $scope.currentDate = new Date();
    $scope.formattedDate = $scope.formatDate($scope.currentDate);
  });

This example demonstrates how to use Moment.js in an AngularJS application to format dates. When you run this example, the formatted date will be displayed on the page using the specified format.

Facebook
Twitter
LinkedIn
Pinterest

Table of Contents

Related posts