how can I format the Typescript date format to display as 09/11/2016 16:16 instead of 9 November 2016 16:16:02 GMT?
Here is the Module class I’ve defined:
export class Module {
constructor(
public id: number,
public name: string,
public description: string,
public lastUpdated: Date,
public owner: string
) { }
getNiceLastUpdatedTime(): String {
let options: Intl.DateTimeFormatOptions = {
day: "numeric", month: "numeric", year: "numeric",
hour: "2-digit", minute: "2-digit"
};
return this.lastUpdated.toLocaleDateString("en-GB", options) + " " + this.lastUpdated.toLocaleTimeString("en-GB", options);
}
}
I need the output to be in DD/MM/YYYY HH:mm format.
Hey Keerti,
To format both the date and time in TypeScript, you should use Date.toLocaleString().
For example:
new Date().toLocaleString()
This will output:
“11/10/2016, 11:49:36 AM”
You can customize the format by specifying locale strings and format options to get the exact output you need.
Hey Keerti Gautam,
In Angular, you should use formatDate instead of DatePipe for formatting dates. Here’s how to do it:
import { formatDate } from ‘@angular/common’;
import { Inject, LOCALE_ID } from ‘@angular/core’;
constructor(@Inject(LOCALE_ID) private locale: string) {
this.dateString = formatDate(Date.now(), ‘yyyy-MM-dd’, this.locale);
}
This will format the current date as yyyy-MM-dd based on the specified locale.
Hey Keerti,
This approach worked well for me. I didn’t need any additional imports beyond what I was already using. formatDate
is quite flexible; you can pass in a date, string, or number. If you prefer not to inject LOCALE_ID
and use this.locale
, you can simply use a string like 'en-US'
.