如何在Flutter(Dart)中在Firebase实时数据库上创建日期格式(ymd)?

huangapple go评论51阅读模式
英文:

How to create Date Format (ymd) on Firebase Realtime Database in Flutter (Dart)

问题

我想将日期保存为时间戳或日期格式,但没有这种字符串类型的选项,如果我将日期作为字符串/DateFormat(ymd)/或任何其他方式,都会显示错误。 代码如下:

MyButton(
  label: "Create",
  onTap: () {
    _validateDate();
    ref.child('Time').push().set({
      'Title': _titleController.text,
      'Place': _subtitleController.text,
      'Date': _selectedDate, // ymd或yyyy/mm/dd或任何其他时间戳
      'Start Time': _startTime,
      'End Time': _endTime
    }).asStream();
    _titleController.clear();
  },
),

_selectedDate 的格式:

DateTime _selectedDate = DateTime.now();

期望的效果:

我希望日期显示为 yyyy/mm/dd 或 dd/mm/yyyy。

英文:

I want to save the date as a timestamp or as a date format but theres no option for that type of string and if I make the date as a string/DateFormat(ymd)/or any other way it shows an error. The Code:

MyButton(
  label: "Create",
  onTap: () {
    _validateDate();
    ref.child('Time').push().set({
      'Title': _titleController.text,
      'Place': _subtitleController.text,
      'Date': _selectedDate, //ymd or yyyy/mm/dd or any other timestamp
      'Start Time': _startTime,
      'End Time': _endTime
    }).asStream();
    _titleController.clear();
  },
),

The _selectedDate format:

DateTime _selectedDate = DateTime.now();

Desired effect:

I want the date to be yyyy/mm/dd or dd/mm/yyyy

答案1

得分: 2

你是对的,FB RTDB 中没有时间戳或日期时间字段类型。此外,不应将日期存储为数据库中的字符串,因为字符串无法方便地处理为日期。在 FB RTDB 中,建议的方法是将日期存储为自纪元以来的毫秒数,这是一个整数。

Flutter/Dart 提供了处理这个整数并将其转换为 DateTime 变量的方法,然后可以轻松地处理、显示为字符串等。

请参阅:https://api.dart.dev/stable/2.19.2/dart-core/DateTime-class.html

英文:

You are correct, there is no timestamp or datetime field type in FB RTDB. Also, you should not store dates as strings on databases as strings cannot be usefully processed as dates. On FB RTDB the recommended approach is to store dates as millisecondssince epoch, which is an integer.

Flutter/Dart provides methods to process this integer into DateTime variables that are then easily processed, displayed as strings, etc.

See: https://api.dart.dev/stable/2.19.2/dart-core/DateTime-class.html

huangapple
  • 本文由 发表于 2023年2月19日 18:44:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75499552.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定