How To Get Date And Time In Angular 4,5,6 And Above Using Datepipe
Solution 1:
Will works on Angular 6 or above
You don't need any 3rd party library. You can format using angular method/util
. import formatDate
from the common package and pass other data. See the below-given example.
import { Component } from'@angular/core';
import {formatDate } from'@angular/common';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
exportclassAppComponent {
today= newDate();
jstoday = '';
constructor() {
this.jstoday = formatDate(this.today, 'dd-MM-yyyy hh:mm:ss a', 'en-US', '+0530');
}
}
stackblitz: https://stackblitz.com/edit/angular-vjosat?file=src%2Fapp%2Fapp.component.ts
Solution 2:
let dateFormat = require('dateformat');
let now = newDate();
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
Thursday,May10th,2018,7:11:21AM
And this format is exactly like your question
dateFormat(now, "dd, mm, yyyy, h:MM:ss TT");
returns 10, 05, 2018 7:26:57 PM
you need npm package npm i dateformat
here is a link for the npm package https://www.npmjs.com/package/dateformat
Here is another question that inspires me How to format a JavaScript date
h:MM:ss TT
results 7:26:57 PM
HH:MM:ss
results 13:26:57
Here is it https://jsfiddle.net/5z1tLspw/
I hope that helps.
Solution 3:
Uses the function formatDate to format a date according to locale rules.
{{ value_expression | date [ : format [ : timezone [ : locale ] ] ] }}
It may be useful:)
Solution 4:
To get formatted date in Angular we can use Angular Datepipe.
For an example we can use following code to get formatted date in our code.
import { DatePipe } from'@angular/common';
@Component({
selector: 'app-name-class',
templateUrl: './name.component.html',
styleUrls: ['./name.component.scss']
})
exportclassNameComponentimplementsOnInit {
// define datepipedatePipe: DatePipe = newDatePipe('en-US');
constructor(){}
// method to get formatted dategetFormattedDate(){
var date = newDate();
var transformDate = this.datePipe.transform(date, 'yyyy-MM-dd');
return transformDate;
}
}
After that you can user getFormattedDate()
method inside your html
code.
<p>{{getFormattedDate()}}</p>
Post a Comment for "How To Get Date And Time In Angular 4,5,6 And Above Using Datepipe"