0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Firestoreで特定の日時以降のデータを取得する

0
Posted at

特定の日付より未来のデータを取得する

  • 例)7月1日以降のデータを取得したい場合
DateTime startDate = DateTime(now.year, 7, 1, 0, 0);
final snapshot = await FirebaseFirestore.instance
  .collection('COLLECTION_NAME') // コレクション名
  .doc('DOCUMENT_ID') // ドキュメントID
  .orderBy('TIMESTAMP_FIELD') // 比較するコレクションのフィールド名
  .startAt([Timestamp.fromDate(startDate)]) // クエリの開始日
  .get();

特定の日付より過去のデータを取得する

  • 例)7月1日以前のデータを取得したい場合
DateTime startDate = DateTime(now.year, 7, 1, 0, 0);
final snapshot = await FirebaseFirestore.instance
  .collection('COLLECTION_NAME') // コレクション名
  .doc('DOCUMENT_ID') // ドキュメントID
  .orderBy('TIMESTAMP_FIELD', descending: true) // // 比較するコレクションのフィールド名
  .startAfter([Timestamp.fromDate(startDate)]) // クエリの開始日
  .get();

Converter

  • FirestoreはTimeStamp型、FlutterはDateTime型なので変換する必要があるため以下のコンバーターを使用したような、しなかったような...
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

class TimestampConverter implements JsonConverter<DateTime, Timestamp> {
  const TimestampConverter();

  @override
  DateTime fromJson(Timestamp value) => value.toDate();

  @override
  Timestamp toJson(DateTime value) => Timestamp.fromDate(value);

  static DateTime? fromJsonNullable(Timestamp? value) => value?.toDate();
}

所感

多分他にもいい方法があるように思いますが、意外とFlutterでTimeStamp型のクエリをしてる記事が少なかったので書いてみました
endAt,endBeforeについても時間があればまとめておきたいですね

参考

https://firebase.google.com/docs/firestore/query-data/query-cursors?hl=ja
https://qiita.com/koffee0522/items/c025e3d7d888c4a9a6e3
https://zenn.dev/sukedon/scraps/94eb764fa021e8

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?