将日期时间对象转换为日期时间字符串,以便我可以将数据插入到 sqflite

时间:2021-05-11 00:00:18

标签: flutter dart flutter-dependencies

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

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

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

<块引用>

'String' 类型的值不能分配给类型的变量 '约会时间'。尝试更改变量的类型,或强制转换 右手边输入'DateTime'。

我能够使用 Intl 包格式化选定的日期和时间...检查图像以了解其格式enter image description here

下面是我的代码... 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();
  }

1 个答案:

答案 0 :(得分: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
}
相关问题