代码之家  ›  专栏  ›  技术社区  ›  LostTexan

在Flutter中设置DateTime变量的时间分量

  •  0
  • LostTexan  · 技术社区  · 2 年前

    我正在将add_2_calendar包添加到我的flutter应用程序中,我需要设置事件发生的时间。

    例如: 我希望活动在2023年12月29日上午10:00开始

    我有一个选择日期的字段(2023年12月29日)和选择时间的字段(上午10:00)。

    我选择日期的字段获取我选择日期时的时间(2023年12月29日下午3:15)。

    如何在数据库的DateTime变量和Timestamp字段中设置未来时间?

    我希望这是有道理的。

    谢谢

    当我将此值写入Cloud Firestore数据库时,它不会捕获我从时间选择器中拾取的时间。

    db字段是一个时间戳字段。保存到数据库的日期是12月29日,但时间是下午12:00:00

    1 回复  |  直到 2 年前
        1
  •  1
  •   Lesig    2 年前

    使用add_2_calendar包在Flutter中设置事件的特定时间并将其保存到Cloud Firestore中,这似乎是一个问题。让我们分解一下这个过程:

    1. 日期时间变量: 当您分别选择日期和时间时,您可以创建 DateTime 变量,并设置日期和时间。例如:

      DateTime selectedDate = // Date picked from the date picker
      TimeOfDay selectedTime = // Time picked from the time picker
      
      DateTime eventDateTime = DateTime(
        selectedDate.year,
        selectedDate.month,
        selectedDate.day,
        selectedTime.hour,
        selectedTime.minute,
      );
      
    2. Firestore时间戳: 将其保存到Cloud Firestore时,请确保将 日期时间 变量到 Timestamp 对象Firestore使用 时间戳 以表示时间。

      import 'package:cloud_firestore/cloud_firestore.dart';
      
      // Assuming 'events' is your Firestore collection
      FirebaseFirestore.instance.collection('events').add({
        'eventDateTime': Timestamp.fromDate(eventDateTime),
        // Other fields...
      });
      

      这应该存储您在中选择的确切日期和时间 eventDateTime 领域

    在读取和写入数据库时,请确保遵循以下步骤以保持一致性。如果问题仍然存在,请检查日期和时间转换逻辑,并确保将值正确传递给Firestore 时间戳 .