I have a view set up in AngularJS and I'm attempting to show the current date in a formatted way. My initial thought was to use
<span>{{Date.now() | date:'yyyy-MM-dd'}}</span>
to display the current date.
I have a view set up in AngularJS and I'm attempting to show the current date in a formatted way. My initial thought was to use
<span>{{Date.now() | date:'yyyy-MM-dd'}}</span>
to display the current date.
To begin, make sure to initialize a date object within your controller:
Controller:
function Controller($scope)
{
$scope.currentDate = new Date();
}
View:
<div ng-app ng-controller="Controller">
{{currentDate | date:'yyyy-MM-dd'}}
</div>
To simplify the process of printing the date without attaching a date object to the current scope each time, you can use a filter in AngularJS:
.filter('todaysDate',['$filter', function($filter) {
return function() {
return $filter('date')(new Date(), 'yyyy-MM-dd');
};
}])
Then, in your HTML view:
<div ng-app="myApp">
<div>{{'' | todaysDate}}</div>
</div>
Custom Date Directive
<span custom-date="MM/dd/yyyy"></span>
Explanation of Custom Directive
.directive('customDate', ['$filter', function($filter) {
return {
link: function( $scope, $element, $attrs) {
$element.text($filter('date')(new Date(), $attrs.customDate));
}
};
}])
This particular directive was created to solve the issue of accessing the Date
object directly in a template. By using this reusable custom directive, you can keep your controllers clean and have a practical inline solution for displaying dates.
Yes, it is possible to achieve this using a mustache expression (
{{new Date() | date:'dd.MM.yyyy HH:mm:ss'}}
). Simply assign the Date object to the scope where you want to evaluate this expression.
Check out this example on jsfiddle: jsfiddle
Keep in mind that the value will not update automatically. Since Angular does not watch this value, you will need to manually trigger digest every time you want it to be updated (for instance, using $interval) which may not be the most efficient use of resources according to the documentation. Consider using directives/controllers to manipulate a smaller child scope for quicker digest.
Just wanted to add my input in case someone comes across this situation :)
My suggestion will yield the same outcome as the current answer, but it is advised to structure your controller in the manner detailed here.
Check out this reference and look for the first "Note" (apologies, there's no anchor)
Here is the recommended approach:
Controller:
var app = angular.module('myApp', []);
app.controller( 'MyCtrl', ['$scope', function($scope) {
$scope.date = new Date();
}]);
View:
<div ng-app="myApp">
<div ng-controller="MyCtrl">
{{date | date:'yyyy-MM-dd'}}
</div>
</div>
In AngularJS, you have the ability to utilize the moment()
and format()
functions.
Controller:
var app = angular.module('demoApp', []);
app.controller( 'demoCtrl', ['$scope', '$moment' function($scope , $moment) {
$scope.date = $moment().format('MM/DD/YYYY');
}]);
View:
<div ng-app="demoApp">
<div ng-controller="demoCtrl">
{{date}}
</div>
</div>
<script type="text/javascript>
var mainApp = angular.module('myapp', [])
mainApp.controller('mycontrol', function ($scope) {
var today = new Date();
console.log($scope.mydate);
var date = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
var current_date = date+'/'+month+'/'+year;
console.log(current_date);
});
</script>
Check out this example of the answer provided: http://plnkr.co/edit/GJfgjCSpzxcWfRiisD4t?p=preview
<span>Date Of Birth: {{DOB | date:"MM-dd-yyyy"}}</span>
<input type="text" datepicker-popup="MM/dd/yyyy" ng-model="DOB" class="form-control" />
Next, make sure to add this in the controller:
$scope.DOB = new Date();
Show
<div ng-app="myapp">
{{CurrentDate.now() | date:'yyyy-MM-dd HH:mm:ss'}}
</div>
Manager
var app = angular.module('myapp',[])
app.run(function($rootScope){
$rootScope.CurrentDate = Date;
})
A different approach inspired by the solution from @Nick G. involves creating a filter named relativedate
, which calculates the date relative to the current date based on the specified difference parameter. For example, (0 | relativedate)
represents today, and (1 | relativedate)
signifies tomorrow.
.filter('relativedate', ['$filter', function ($filter) {
return function (rel, format) {
let date = new Date();
date.setDate(date.getDate() + rel);
return $filter('date')(date, format || 'yyyy-MM-dd')
};
}]);
Here is an example of how you can use this filter in your HTML:
<div ng-app="myApp">
<div>Yesterday: {{-1 | relativedate}}</div>
<div>Today: {{0 | relativedate}}</div>
<div>Tomorrow: {{1 | relativedate}}</div>
</div>
If you're looking for an alternative approach: Create a new variable in your Controller to store the current date, like this:
var eventsApp = angular.module("eventsApp", []);
eventsApp.controller("EventController", function EventController($scope)
{
$scope.myDate = Date.now();
});
Then, in your HTML file, add the following code:
<!DOCTYPE html>
<html ng-app="eventsApp">
<head>
<meta charset="utf-8" />
<title></title>
<script src="lib/angular/angular.js"></script>
</head>
<body>
<div ng-controller="EventController">
<span>{{myDate | date : 'yyyy-MM-dd'}}</span>
</div>
</body>
</html>
Can anyone assist me in developing a custom filter or directive that will substitute a word for a template? As an example, I want to replace the word 'NEW' with the template 'isnew.html' in the text "My product NEW". Any help would be g ...
<!-- if (index == 2) <div>{{data.customText}}</div> --> <div ng-repeat-start="product in products">{{product.headline}}</div> <div ng-repeat-end>{{product.text}}</div> Suppose I am presenting a lineup of 5 product ...
Hello, StackOverflow community! This is my initial post here and I'm excited to seek guidance. I recently created a delete route in Express to delete both a user and their profile: // @route DELETE api/profile/ // @desc Delete user and profile / ...
Currently tackling a challenging e-commerce project and facing an obstacle with the following component: import React, { useEffect, useState } from 'react'; const Cart = () => { let [carts, setCarts] = useState([]); let [price, se ...
I am encountering an issue with JSON. Since I am not proficient in JSON, identifying the problem is challenging. Here is the JSP code snippet. $(document).ready( function(){ window.onload = dept_select; $("#sales_dept_id").change ...
I am working on a Vue.js form component with multiple input fields, but now I need to split it into two separate forms that will collect different user input. Form 1 includes: Name Surname Email with a form name attribute value of form_1 Form 2 i ...
I've created a custom hook that checks if a user is logged in and redirects them to the login page if not. Below is a simplified version of the hook assuming the user is not logged in: import { useRouter } from 'next/router'; export default ...
Is there a way to utilize jQuery/Javascript for selecting the HTML content of the two <p> elements in the initial <div class="description? I'm open to using Regex as well. This specific jQuery selection is being executed within Node.js on a c ...
I am attempting to implement my own custom palette option in the theme section, but I am struggling with how to do the augmentation part using TypeScript. So far, I have created a file named "material-ui.d.ts" and inside it, I only have: import { PaletteO ...
Within my asp.net application, there is an image tag linking to another aspx file in the src attribute, displaying a picture. <img src="/picture.aspx?Param=3" alt="picture"/> I need to convert the image tag into a div with a background-image proper ...
I have been trying to send data from the frontend to the backend of my website using AJAX. Below is the post request view in my Django views: def post(self, request): id_ = request.GET.get('teacherID', None) print(id_) args = {} ...
I am currently developing an application that combines Angular and MusicKit to offer users the ability to listen to music simultaneously. However, I encountered a challenging error when trying to run the application using ng serve --host x.x.x.x instead of ...
Hi everyone, I am new to JavaScript. I am currently working on creating two dropdown lists, one for 'Start Time' and another for 'End Time'. These dropdown lists will display hours in a 24-hour format with intervals of 30 minutes. In t ...
I have a 3D model that I initially had in the 3DS format. I then converted it to OBJ and finally to JS format. Now, my goal is to load this model into another JS file. Below you'll find the code snippet I've written for this purpose: var loader ...
I need to design an Angular grid where the last column remains frozen. This frozen column should display the summation of all row values, and the last row should be editable. I am able to create the Angular grid itself, but I am struggling with how to stru ...
When I make a call to this url, the response is a JSON object when done directly in the browser. However, when I try to do it via ajax using the following code snippet: $.ajax({ url: url, type: "GET", dataType:"jsonp", succ ...
I have a ng-repeat loop with dates in the format below: <small>Added: <strong>{{format(contents.completeddate)}}</strong></small> I am using a datepicker plugin that provides me with 2 objects - a start date and an end date. For ...
When inputting special characters into the field used for storing the alphanumeric serial number, they are accepted. I need to prevent special characters from being entered in the input field. <ion-input [(ngModel)]="serial_number" (ngModelCha ...
I am attempting to showcase my data in a table using Underscore.js. Below is the div container class I am working with: <div id="container"></div> Upon window load, I have added an event listener: window.addEventListener("load", function(ev ...
Is it possible to create an inline expression for ng-hide in the following manner: ng-hide="userType!=user" Please advise on how to achieve this. ...