【问题标题】:How to change the datetime format in sqflite database so that it displays only date?如何更改 sqflite 数据库中的日期时间格式,使其仅显示日期?
【发布时间】:2020-06-02 02:52:47
【问题描述】:

希望你能帮我解决这个问题!这几天我一直在扯头发,所以任何帮助都将不胜感激。

我想在我当前项目的 sqflite 表中添加一个“日期”列。这是 database_helper.dart 的代码:

import 'dart:io';

import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';

class DatabaseHelper {

  static final _databaseName = "MyDatabase.db";
  static final _databaseVersion = 1;

  static final table = 'my_table';

  static final columnId = '_id';
  static final columnName = 'name';
  static final columnAge = 'age';
  static final columnColour = 'colour';
  static final columnDateTime = 'datetime';

  // make this a singleton class
  DatabaseHelper._privateConstructor();
  static final DatabaseHelper instance = DatabaseHelper._privateConstructor();

  // only have a single app-wide reference to the database
  static Database _database;
  Future<Database> get database async {
    if (_database != null) return _database;
    // lazily instantiate the db the first time it is accessed
    _database = await _initDatabase();
    return _database;
  }

  // this opens the database (and creates it if it doesn't exist)
  _initDatabase() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, _databaseName);
    return await openDatabase(path,
        version: _databaseVersion,
        onCreate: _onCreate);
  }

  // SQL code to create the database table
  Future _onCreate(Database db, int version) async {
    await db.execute('''
          CREATE TABLE $table (
            $columnId INTEGER PRIMARY KEY,
            $columnName TEXT NOT NULL,
            $columnAge INTEGER NOT NULL,
            $columnColour TEXT NOT NULL,
            $columnDateTime TEXT NOT NULL
          )
          ''');
  }

  // Helper methods

  // Inserts a row in the database where each key in the Map is a column name
  // and the value is the column value. The return value is the id of the
  // inserted row.
  Future<int> insert(Map<String, dynamic> row) async {
    Database db = await instance.database;
    return await db.insert(table, row);
  }

  // All of the rows are returned as a list of maps, where each map is
  // a key-value list of columns.
  Future<List<Map<String, dynamic>>> queryAllRows() async {
    Database db = await instance.database;
    return await db.query(table);
  }

  // All of the methods (insert, query, update, delete) can also be done using
  // raw SQL commands. This method uses a raw query to give the row count.
  Future<int> queryRowCount() async {
    Database db = await instance.database;
    return Sqflite.firstIntValue(await db.rawQuery('SELECT COUNT(*) FROM $table'));
  }

  // We are assuming here that the id column in the map is set. The other
  // column values will be used to update the row.
  Future<int> update(Map<String, dynamic> row) async {
    Database db = await instance.database;
    int id = row[columnId];
    return await db.update(table, row, where: '$columnId = ?', whereArgs: [id]);
  }

  // Deletes the row specified by the id. The number of affected rows is
  // returned. This should be 1 as long as the row exists.
  Future<int> delete(int id) async {
    Database db = await instance.database;
    return await db.delete(table, where: '$columnId = ?', whereArgs: [id]);
  }
}

这是 main.dart 的代码:

import 'package:flutter/material.dart';
// change `flutter_database` to whatever your project name is
import 'package:flutter_database/database_helper.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'SQFlite Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {

  // reference to our single class that manages the database
  final dbHelper = DatabaseHelper.instance;

  // homepage layout
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('sqflite'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              child: Text('insert', style: TextStyle(fontSize: 20),),
              onPressed: () {_insert();},
            ),
            RaisedButton(
              child: Text('query', style: TextStyle(fontSize: 20),),
              onPressed: () {_query();},
            ),
          ],
        ),
      ),
    );
  }

  // Button onPressed methods

  void _insert() async {
    
    // row to insert
    Map<String, dynamic> row = {
      DatabaseHelper.columnName : 'Bob',
      DatabaseHelper.columnAge  : 23,
      DatabaseHelper.columnColour : 'Red',
      DatabaseHelper.columnDateTime : DateTime.now().toIso8601String(),
    };
    final id = await dbHelper.insert(row);
    print('inserted row id: $id');
  }

  void _query() async {
    final allRows = await dbHelper.queryAllRows();
    print('query all rows:');
    allRows.forEach((row) => print(row));
  }

}

我们的目标是简单地将今天的日期记录下来——我不需要记录其中的一部分,只需记录日期即可。如果您运行上面的代码,如果您单击“查询”按钮,日期时间会显示在控制台中,但我希望它只存储今天的日期,而不是时间。

我查看了 intl 包的文档,因为我读到这是格式化日期的好方法,但在这种情况下我不知道如何在我的代码中实现它。

任何想法将不胜感激!

非常感谢,

杰森

【问题讨论】:

  • sqlite.org/datatype3.html#date_and_time_datatype,列表中的最后一个选项
  • 感谢您的回复。不过还在努力解决!你的意思是我应该把它转换成一个整数而不是 toIso8601String()?
  • 是的,这是最灵活的格式
  • 好的,非常感谢,我会玩一下代码。为您的帮助喝彩!
  • 当然,欢迎您-查看DateFormat官方文档

标签: datetime flutter sqflite


【解决方案1】:

是的,您可以使用 intl 的DateFormatter

import 'package:intl/intl.dart';
import 'package:test/test.dart';

void main() {
  final DateFormat dateOnlyFormat = DateFormat('yyyy.MM.dd');
  test(
      'assert that dateOnlyFormat returns only date part of a DateTime '
      'instance', () {
    final DateTime givenDateTime = DateTime(1995, 1, 1, 5, 5, 5, 5, 5);
    expect(dateOnlyFormat.format(givenDateTime), "1995.01.01");
  });

  test('assert that dateOnlyFormat parses the date as expected', () {
    const String givenDateString = "1995.01.01";
    expect(dateOnlyFormat.parse(givenDateString), DateTime(1995, 1, 1));
  });
}

如果您需要以其他方式自定义日期格式,请参阅DateFormat 的类文档。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-30
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    • 2018-03-27
    相关资源
    最近更新 更多