【问题标题】:Select data from sqlite3 before or after a certain date using Typeorm使用 Typeorm 在某个日期之前或之后从 sqlite3 中选择数据
【发布时间】:2021-07-03 06:43:41
【问题描述】:

我想选择sqlite中某个日期之前或之后的数据,使用Typeorm,其中日期在milliseconds中。

这是我的Query Builder

  const qb = getConnection()
    .getRepository(Post)
    .createQueryBuilder('p')
    .where('createdAt < :cursor', {
       cursor: "1624809058000"
     })
    .getMany()

【问题讨论】:

    标签: javascript database typescript sqlite typeorm


    【解决方案1】:

    我们必须以这种格式传递日期:"yyyy-mm-dd HH:MM:ss.l" 示例:"2000-01-01 00:00:00.000"
    所以,我们必须把日期转换成这种格式。

    1. 第一个解决方案
      const chars = { T: ' ', Z: '' }
      const dateInMilliseconds = "1624809058000"
      const qb = getConnection()
        .getRepository(Post)
        .createQueryBuilder('p')
        .where('createdAt < :cursor', {
           cursor: new Date(parseInt(dateInMilliseconds))
             .toISOString()
             .replace(/[TZ]/g, ch => chars[ch])
         })
        .getMany()
    
    1. 第二种解决方案
    import { LessThan, MoreThan } from 'typeorm'
    import { format } from 'date-fns'
    
    // TypeORM Query Operators
    const MoreThanDate = (date: Date) => MoreThan(format(date, 'yyyy-mm-dd HH:MM:SS'))
    const LessThanDate = (date: Date) => LessThan(format(date, 'yyyy-mm-dd HH:MM:SS'))
    
    const dateInMilliseconds = "1624809058000"
    const posts = await Post.find({
        createdAt: MoreThanDate(new Date(dateInMilliseconds))
    })
    
    1. 第三种解决方案
    import { Between } from 'typeorm';
    import { addYears, subYears } from 'date-fns';
    
    // TypeORM Query Operators
    const MoreThanDate = (date: Date) => Between(date, addYears(date, 100));
    const LessThanDate = (date: Date) => Between(subYears(date, 100), date);
    
    const dateInMilliseconds = "1624809058000"
    const posts = await Post.find({
      where: {
        createdAt: MoreThanDate(new Date(dateInMillisecons)),
      },
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2012-07-24
      • 1970-01-01
      • 1970-01-01
      • 2012-11-13
      • 2022-01-17
      相关资源
      最近更新 更多