Search code examples
postgresqltypeorm

How to do a query of DAY_ONLY on a DateTime field?


I have a entity like this

import { Field, ObjectType } from "type-graphql";
import {
  BaseEntity,
  Column,
  CreateDateColumn,
  Entity,
  ManyToOne,
  OneToMany,
  PrimaryGeneratedColumn,
} from "typeorm";
import { Brand } from "./Brand";
import { Price } from "./Price";
import { UserComment } from "./UserComment";

@ObjectType()
@Entity()
export class Product extends BaseEntity {
  @Field()
  @PrimaryGeneratedColumn()
  id!: number;

  //...

  @Field()
  @CreateDateColumn()
  createdAt: Date;
}

In postgresql database, createdAt is stored like this

2022-04-06 18:13:18.141658

Example , i want to get all product of today, How can i do it?


Solution

  • In postgreSQL we can convert to date by suffixing with ::date.
    Here createdAt is datatype timestamp.
    This article treats the subject in greater depth https://wanago.io/2021/03/15/postgresql-typeorm-date-time/

    select
      createdAt AsDateTime,
      createdAt::date AsDate
    from myTable;
    
    asdatetime          | asdate    
    :------------------ | :---------
    2022-02-01 10:11:15 | 2022-02-01
    

    db<>fiddle here