I need to insert the dates in dd/mm/yyyy format to match the other technologies in my application. I am using Nestjs, TypeOrm and Postgresql as database.
I tried to use the @Transform decorator like in the documentation
@Transform(({ value }) => moment(value).format('DD/MM/YYYY'))
@Column()
encoded_date: Date;
Except that it always inserts a timestamp and returns a timestamp.
Is it possible to have a similar behavior to_date(’25/02/2023′, ‘DD/MM/YYYY’)::date, as one does in an sql script ? And Keeping Date type ?
I also tried this and that’s give me yyyy-mm-dd but no way to format
like dd/mm/yyyy
@CreateDateColumn({type:'date'})
encoded_date: Date;
2
Answers
On db-end, you can alter your
datestyle
setting to modify default input text-to-date and output date-to-text formats (see also here). As with most settings:SET
of its ownYou can also interface with your data through formatting functions in both directions, using:
to_date(your_date,'DD/MM/YYYY')
on input, which you mentionedto_char(your_date,'DD/MM/YYYY')
on output.demo
As to the underlying format of the
date
/time
/timestamp
, with or without timezone: it’s always just a number. Postgres uses the format mask given or implied by settings to calculate an epoch, then the timezone implied by settings or a supplied time zone name or offset, to shift it to internal UTC – and after that it doesn’t keep them. These types are meant to hold a when. Where and how help pinpoint the exact, absolute when, but they aren’t its integral elements, so the source timezone and format it came in are discarded unless saved separately.You can use custom transfomer than converts input string to Date object.