typescript - 在 TypeScript 中使用 AM/PM 的日期之间过滤对象数组
问题描述
我正在使用 Angular 8 (TypeScript) 和 Firebase Firestore 做一个 Web 应用程序。我有一个名为createdAt
type的字段的文档firebase.firestore.Timestamp
。我正在使用 AM/PM 将日期保存在 Firestore 中。
export interface Client {
id: number;
name: string;
createdAt: firebase.firestore.Timestamp;
}
我要过滤的数组是(这是我从 Firestore 收到的):
const clients = [
{
"createdAt":{
"seconds": 1564753299,
"nanoseconds": 89000000
},
"id":1,
"name":"Juana",
},
{
"createdAt":{
"seconds": 1564753323,
"nanoseconds": 418000000
},
"id":2,
"name":"",
},
{
"createdAt":{
"seconds": 1564839675,
"nanoseconds": 906000000
},
"id":3,
"name":"Ramon",
},
{
"createdAt":{
"seconds": 1564839684,
"nanoseconds": 944000000
},
"id":4,
"name":"",
}
];
我正在尝试像这样过滤数组:
filterClients() {
const from = new Date(this.fromDate.year, this.fromDate.month - 1, this.fromDate.day, 0, 0, 0);
const to = new Date(this.toDate.year, this.toDate.month - 1, this.toDate.day, 23, 59, 0);
this.clients = this.clientsCopy.filter(client =>
client.createdAt.toDate().getTime() >= from.getTime() &&
client.createdAt.toDate().getTime() <= to.getTime());
}
如果我从 8 月 2 日到 8 月 3 日过滤数组,则会丢失 8 月 3 日的数据。比较日期时我做错了什么?我看到了其他解决方案并尝试了它们,但是,在我的情况下,出于某种原因,比较是跳过数据。
我的目标是过滤数组以仅获取一系列日期之间的数据。
解决方案
您的问题可能与Date
正确使用带有本地时区的 JavaScript 中的 API 有关。如果您通过它们的 Unix 时间戳 ( date.getTime()
) 比较两个日期,则必须确保两者都基于 UTC 或在日期的构建时间您的本地时区(或其他统一时区)。
我可以想象,时间戳在 Firebase 中以 UTC 格式保存。当您像这样定义日期过滤器范围时,
const from = new Date(2019, 7, 2, 0, 0, 0);
const to = new Date(2019, 7, 3, 23, 59, 0);
将构建一个考虑您的本地时区并调整其底层 Unix 时间戳的日期(请参见此处)。Firebase: UTC <--> client: local timezone
,因此您将苹果与橙子进行比较。
您可以使用Date.UTC来构建您的客户日期:
const from = new Date(Date.UTC(2019, 7, 2, 0, 0, 0));
const to = new Date(Date.UTC(2019, 7, 3, 23, 59, 0));
或使用其中一种日期转换方法。
希望,这会有所帮助。
推荐阅读
- node.js - MongoDB合并三个集合并得到结果
- javascript - 使用正则表达式删除连续的重复字符
- powershell - Powershell 从 Box 中获取链接
- spring - 在 Spring Boot 中配置 Kafka 消费者 = 失去对消费者行为的控制?
- c++ - RInside - 包装 C++ 函数以在 R 函数中使用
- swift - Swift Codable:使用动态键编码结构
- python - 根据另一个使用字符串对熊猫数据框进行分类包含
- django - 将数据从 datepicker 表单传递到 APIView
- java - javax.persistence.QueryTimeoutException:无法获取 JDBC 连接 spring boot hibernate + jpa
- python - 使用 Python 迭代 JSON 对象