【问题标题】:Convert a DateTime Object to Datetime String so i can insert data to sqflite将日期时间对象转换为日期时间字符串,以便我可以将数据插入 sqflite
【发布时间】:2021-08-01 08:36:21
【问题描述】:

我正在构建一个待办事项应用程序,用户必须在其中安排要在特定日期和时间执行的任务。

我已经能够按照我在网上看到的教程构建我的日期和时间选择器,但现在我正在尝试使用颤振 SQflite 将选定的日期和时间保存到 SQL,我读到现在我们可以'不将 DateTime 对象直接保存到数据库中,除非它已被转换为 String 或 Int。

现在我在转换它时遇到问题...可能是因为我不知道它是如何完成的,我不断收到错误

“字符串”类型的值不能分配给类型的变量 '约会时间'。尝试更改变量的类型,或强制转换 右侧键入“日期时间”。

我能够使用 Intl 包格式化所选日期和时间...检查图像以查看其格式化方式

这是我下面的代码... selectedDayAndTime 是我要更改为字符串的 DateTime 对象

import './model.dart';

class TodoItem extends Model {
  static String table = 'todo_items';

  int id;
  String title;
  String description;
  String date;
  bool complete;

  TodoItem({this.id, this.title, this.description, this.date, this.complete});

  Map<String, dynamic> toMap() {
    Map<String, dynamic> map = {
      'title': title,
      'description': description,
      'date': date,
      'complete': complete,
    };

    if (id != null) {
      map['id'] = id;
    }
    return map;
  }

  static TodoItem fromMap(Map<String, dynamic> map) {
    return TodoItem(
        id: map['id'],
        title: map['title'],
        description: map['description'],
        date: map['date'],
        complete: map['complete'] == 1);
  }
}

然后是我的数据库代码

import 'dart:async';
import '../models/model.dart';
import 'package:sqflite/sqflite.dart';

abstract class DB {
  static Database _db;

  static int get _version => 3;

  static Future<void> init() async {
    if (_db != null) {
      return;
    }

    try {
      String _path = await getDatabasesPath() + 'example';
      _db = await openDatabase(_path, version: _version, onCreate: onCreate);
    } catch (ex) {
      print(ex);
    }
  }

  static void onCreate(Database db, int version) async => await db.execute(
      'CREATE TABLE todo_items (id INTEGER PRIMARY KEY NOT NULL, title STRING NOT NULL, description STRING, date TEXT, complete BOOLEAN)');


  static Future<int> insert(String table, Model model) async =>
      await _db.insert(table, model.toMap());
}

然后在我的 Main.dart 文件中

class _MyHomePageState extends State<MyHomePage> {
  // String _task;
  String titleInput;
  String descriptionInput;
  DateTime selectedDateAndTime;

  List<TodoItem> _tasks = [];
Future _selectDayAndTimeL(BuildContext context) async {
    DateTime _selectedDay = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2021),
        lastDate: DateTime(2030),
        builder: (BuildContext context, Widget child) => child);

    TimeOfDay _selectedTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );

    if (_selectedDay != null && _selectedTime != null) {
      //a little check
    }
    setState(() {
      selectedDateAndTime = DateTime(
        _selectedDay.year,
        _selectedDay.month,
        _selectedDay.day,
        _selectedTime.hour,
        _selectedTime.minute,
      );
      // _selectedDate = _selectedDay;
    });
    // print('...');
  }

// This is the Save function
void _save() async {
    Navigator.of(context).pop();
    TodoItem item = TodoItem(
        title: titleInput,
        description: descriptionInput,
        date: selectedDateAndTime,
        complete: false);

    await DB.insert(TodoItem.table, item);
    setState(() {
      titleInput = '';
      descriptionInput = '';
      selectedDateAndTime = ''; // I tried this but kept getting that same error
    });
    refresh();
  }

【问题讨论】:

    标签: flutter dart flutter-dependencies


    【解决方案1】:

    您可以通过 2 种方法轻松转换和还原 DateTime,以便将它们保存到数据库:

    1. 转换为格式化字符串:
    void main() {
      var dt = new DateTime.now();
      var formatter = new DateFormat('yyyy-MM-dd HH:mm:ss');
      String formatted = formatter.format(dt); // Save this to DB
      print(formatted); // Output: 2021-05-11 08:52:45
      print(formatter.parse(formatted)); // Convert back to DateTime object
    }
    
    1. 转换为 UNIX 时间:
    void main() {
      final dt = DateTime.now();
      final dtInEpoch = dt.millisecondsSinceEpoch; // Save this to DB
      print(dtInEpoch); // Output: 1620697965915
      print(DateTime.fromMillisecondsSinceEpoch(dtInEpoch)); // Convert back to DateTime object
    }
    

    【讨论】:

    • 我试图让选定的日期和时间显示在 Listtile 字幕中,但它没有显示...只是空白...他是我尝试使用的代码subtitle: Text(formatted != null ? formatted : 'Default date'),还尝试调用 Date 以查看是否调用了错误的函数,但仍然给出相同的问题subtitle: Text( item.date != null ? item.date : 'Defualt Date And Time', ),'
    • 这就是我添加你给String formatted; DateTime selectedDateAndTime;void mainn() { var dt = new DateTime.now(); var formatter = new DateFormat('yyyy-MM-dd HH:mm:ss'); String formatted = formatter.format(dt); // Save this to DB print(formatted); // Output: 2021-05-11 08:52:45 print(formatter.parse(formatted)); // Convert back to DateTime object }的修复方法
    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 2022-01-26
    • 2022-08-18
    • 2015-09-17
    • 2016-12-02
    • 2017-08-04
    • 2014-12-13
    相关资源
    最近更新 更多