When using TypeORM for database management, the default date format typically depends on the underlying database system, such as PostgreSQL, MySQL, etc. However, sometimes we need to change this date format at the application level, especially during data interaction or report generation.
To change the default date format to dd/mm/yyyy in TypeORM, we can use the following methods:
1. Formatting Data on Retrieval
After retrieving data at the application layer, use JavaScript date handling libraries such as date-fns or moment.js to format the date. This approach does not alter the storage format in the database; it only modifies the display or transmission of data.
javascriptimport { format } from 'date-fns'; const repository = dataSource.getRepository(Entity); const data = await repository.find(); const formattedData = data.map(item => { return { ...item, dateField: format(new Date(item.dateField), 'dd/mm/yyyy') }; });
2024年6月29日 12:07 回复