Reputation: 1215
I need to get the year, the month and the date from a specific date that's coming from back-end. How can I do that on the front-end controller?
Thanks!
Upvotes: 0
Views: 35071
Reputation: 11
In AngularJS (not Angular 2+) you can use the date filter. This will format a date to a given string based on the format provided. For your situation you can use the following:
{{ createdDate | date : ['yyyy'] }} // this will give a 4 digit representation of the year
{{ createdDate | date : ['MMM'] }} // month in year (January-December)
{{ createdDate | date : ['d'] }} // day in month (1-31)
Link to demo on Plunker
Upvotes: 0
Reputation: 1493
Example
In your HTML
<div>site design / logo © {{copyright | date:'yyyy'}} Stack Exchange Inc</div>
In your AngularJS Controller
$scope.copyright = new Date();
The output will be
/*site design / logo © 2019 Stack Exchange Inc; */
To Answer your Question
Controller
$scope.dateVariable = new Date();
To get Year in view
{{dateVariable | date:'yyyy'}}
To get Month in view
{{dateVariable | date:'MM'}}
To get Day in view
{{dateVariable | date:'dd'}}
For more options such as getting the full date, different ways to display the date, getting the time and getting options on different things/ways to display date items
The General Syntax is
{{ date | date : format : timezone }}
And the output options can be found listed here or here
Upvotes: 4
Reputation: 1955
Let's say the variable name for the date coming from the backend is D
.
you can do:
var date = new Date(D);
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDay();
Upvotes: 5