To display dates in a specific format, you can use the date filter.
Within the .ts file (TypeScript):
// Variables used in HTML
let dateString = '2002-07-25T00:00:00';
let newDate = new Date(dateString);
// Format date in TypeScript
getFormattedDate(date: Date, format: string) {
const datePipe = new DatePipe('en-US');
return datePipe.transform(date, format);
}
// Convert date to user's timezone
const localDate: Date = this.convertToLocalDate('02/10/2022');
convertToLocalDate(responseDate: any) {
try {
if (responseDate != null) {
if (typeof (responseDate) === 'string') {
if (String(responseDate.indexOf('T') >= 0)) {
responseDate = responseDate.split('T')[0];
}
if (String(responseDate.indexOf('+') >= 0)) {
responseDate = responseDate.split('+')[0];
}
}
responseDate = new Date(responseDate);
const newDate = new Date(responseDate.getFullYear(), responseDate.getMonth(), responseDate.getDate(), 0, 0, 0);
const userTimezoneOffset = newDate.getTimezoneOffset() * 60000;
const finalDate: Date = new Date(newDate.getTime() - userTimezoneOffset);
return finalDate > Util.minDateValue ? finalDate : null;
} else {
return null;
}
} catch (error) {
return responseDate;
}
}
Within the HTML:
{{dateString | date:'MM/dd/yyyy'}}
Here are some formats that you can implement:
For the Backend:
public todayDate = new Date();
HTML :
<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option>
</select>