Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get current date with 'yyyy-MM-dd' format in Angular 4

Tags:

angular

How i can get the current date with a specific format 'yyyy-MM-dd', for today by example i with that the result be: '2018-07-12', with using just the command

myDate = new Date(); 

thanks a lot

like image 514
Hazem HASAN Avatar asked Jul 12 '18 07:07

Hazem HASAN


People also ask

How do I get the current date in angular 10?

We'll get the current date by using the date() method in the app. component. ts file. Copy # Angular today = new Date();

How do I change the format of a date in TypeScript?

To format a date or time in TypeScript, we can use the date's toLocaleString method. const s = new Date(). toLocaleString(); to create a new Date object and then call toLocaleString on it to return a string that has the formatted datetime of the current time formatted according to the current locale.


1 Answers

You can use DatePipe for formatting Date in Angular.

In ts if you want to format date then you can inject DatePipe as Service in constructor like this

import { DatePipe } from '@angular/common';  @Component({     templateUrl: './name.component.html',     styleUrls: ['./name.component.scss'],     providers: [DatePipe] })  myDate = new Date(); constructor(private datePipe: DatePipe){     this.myDate = this.datePipe.transform(this.myDate, 'yyyy-MM-dd'); } 

And if you want to format in html file, 'Shortdate' will return date of type MM/DD/YY

{{myDate | date: 'shortDate' }} 

As of Angular 6, this also works,

import {formatDate} from '@angular/common';  formatDate(new Date(), 'yyyy/MM/dd', 'en'); 
like image 192
khush Avatar answered Sep 25 '22 01:09

khush