I'm using angular 14. I've an object where key-value is this:
processStartDate: Date Wed May 10 2023 05:30:00 GMT 0530 (India Standard Time)
I want to convert that timestamp to just 'mm/dd/yyyy'.
I tried this:
finalStartDate: new SimpleDateFormat("MM/dd/yyyy").format(new Date(this.processStartDate));
But it says: "Cannot find name 'SimpleDateFormat'.ts(2304)". Please help me.
CodePudding user response:
You can create this custom function in a common file and access it wherever you want.
export function formatDate(date: Date): string {
if (isNaN(date.getTime())) {
return '';
} else {
const month = date.getMonth() 1;
const day = date.getDate();
const year = date.getFullYear();
return ('00' month).slice(-2) '/' ('00' day).slice(-2) '/' year;
}
}
finalStartDate = formatDate(new Date(this.processStartDate));
CodePudding user response:
Try this:
date.toLocaleDateString('en-US', {month:'2-digit', day: '2-digit',
year:'numeric'});
You might have to register the Locale like this:
import { registerLocaleData } from '@angular/common';
import localeEn from '@angular/common/locales/en';
import localeEnExtra from '@angular/common/locales/extra/en';
registerLocaleData(localeEn, 'en-US', localeEnExtra);