简体   繁体   English

Select Firebase firestore 集合,其中时间戳为今天

[英]Select Firebase firestore collection where timestamp is today

Good day everybody,大家好,

I have a firetore collection of docs which all have a dateCreated field of timestamp data type.我有一个 firetore 文档集合,它们都具有时间戳数据类型的 dateCreated 字段。 I want to select all the docs where dateCreated is today.我想 select 今天 dateCreated 的所有文档。 How would I achieve this.我将如何实现这一目标。 I have tried below with no success我在下面尝试过但没有成功

const ref = firestore.collection('orders').where('dateCreated','<',moment().toDate()).orderBy('dateCreated', 'desc');

The above line gets all the orders from the collection and I want all the orders that was created today.上面的行从集合中获取所有订单,我想要今天创建的所有订单。 Hope this makes sense希望这是有道理的

Thanks Everyone感谢大家

If you are talking relative to the user's own timezone and not based on a fixed timezone (eg you are on the east coast, but HQ is on the west coast), you can use this:如果您谈论的是相对于用户自己的时区而不是基于固定时区(例如,您在东海岸,但总部在西海岸),您可以使用:

// for numeric timestamp values (milliseconds since 1970-01-01 UTC)
const midnightThisMorning = (new Date()).setHours(0,0,0,0);

const ref = firestore.collection('orders')
  .where('dateCreated', '>', midnightThisMorning)
  .orderBy('dateCreated', 'desc');
// for firebase.firestore.Timestamp values
const startDate = new Date();
startDate.setHours(0,0,0,0);

const ref = firestore.collection('orders')
  .where('dateCreated', '>', startDate)
  .orderBy('dateCreated', 'desc');

If you know that the time must be relative to a particular timezone, you need to calculate midnight based on that timezone instead.如果您知道时间必须与特定时区相关,则需要根据该时区计算午夜。

// for numeric timestamp values (milliseconds since 1970-01-01 UTC)
const midnightInLA = moment()
  .tz("America/Los_Angeles")
  .startOf("day")
  .valueOf();

const ref = firestore.collection('orders')
  .where('dateCreated', '>', midnightInLA)
  .orderBy('dateCreated', 'desc');
// for firebase.firestore.Timestamp values
const dateMidnightInLA = moment()
  .tz("America/Los_Angeles")
  .startOf("day")
  .toDate();

const ref = firestore.collection('orders')
  .where('dateCreated', '>', dateMidnightInLA)
  .orderBy('dateCreated', 'desc');

Note: With moment-timezone , if you are only using select timezones you can deploy your code with the details for those timezones rather than all timezones.注意:使用moment-timezone ,如果您只使用 select 时区,您可以使用这些时区而不是所有时区的详细信息来部署您的代码。 This process is detailed in the documentation .此过程在文档中有详细说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM