Britchi3
Britchi3

Reputation: 180

Convert a DateTime Object to Datetime String so i can insert data to sqflite

I am building a To-do app where a user will have to schedule a task to be performed in a particular day and time.

I have been able to build my Date and Time picker following a tutorial I saw online, but now I am trying to save the selected-date-and-time to SQL using the flutter SQflite, I read that for now we can't save a DateTime object to the database directly except it's been converted to String or Int.

Now I am having issues converting it... maybe because I don't know how it's done, I keep getting the error

A value of type 'String' can't be assigned to a variable of type 'DateTime'. Try changing the type of the variable, or casting the right-hand type to 'DateTime'.

I was able to format the Selected Date and Time using the Intl package... check the image to see how its been formatted enter image description here

This are my codes bellow ... selectedDayAndTime is the DateTime object that i want to change to string

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);
  }
}

Then my DB codes

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());
}

Then On my Main.dart file

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();
  }

Upvotes: 0

Views: 3766

Answers (1)

Bach
Bach

Reputation: 3326

You can easily convert and revert the DateTime in 2 methods, in order to save them to database:

  1. Convert to Formatted string:
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. Convert to UNIX time:
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
}

Upvotes: 1

Related Questions