Is there an easy way to format the date time in Angular/Typescript in “yyyy-MM-dd’T’HH:mm:ss.SSSZ”
I got the current date by doing
JavaScript
x
3
1
const currentDate = new Date().toLocaleDateString('What should I add here')
2
3
Can you please tell me what do I need to add here in the method to get in format of yyyy-MM-dd’T’HH:mm:ss.SSSZ
Advertisement
Answer
There are two ways to achieve this:
- The Angular way using
DatePipe
In you component, you can inject DatePipe
from @angular/common
and call on the transform
method to format date. Here is the list from Angular docs of options you can use to format date and time.
JavaScript
1
10
10
1
import { DatePipe } from '@angular/common';
2
3
class AppComponent {
4
constructor(private datePipe: DatePipe) {}
5
6
someMethod() {
7
const date = this.datePipe.transform(new Date(), 'yyyy-MM-ddThh:mm:ss.SSSZ');
8
}
9
}
10
In the module, where you have defined this component, you need to provide DatPipe
as providers
JavaScript
1
8
1
@NgModule({
2
imports: [ BrowserModule, FormsModule ],
3
declarations: [ AppComponent],
4
bootstrap: [ AppComponent ],
5
providers: [ DatePipe ]
6
})
7
export class AppModule { }
8
- Second way would be to use native
toISOString()
method
JavaScript
1
2
1
const date = (new Date()).toISOString();
2