Flutter Sqflite中日期格式为dd-MM-yyyy时如何获取最近24小时记录
解决sqflite筛选最近24小时记录的问题
当前你的date字段仅存储了dd-MM-yyyy格式的日期(无时分秒),无法精准筛选最近24小时的记录,需要先调整时间存储方式,再修改查询逻辑。
步骤1:修改时间存储格式
推荐两种实用方案:
方案A:存储时间戳(SQLite时间比较最优选择)
修改createItem函数,将时间存储为毫秒级时间戳:
//method to create an item to insert into the database table static Future<int> createItem( String exercise_name, String? total_weight, String? total_reps, ) async { DateTime now = DateTime.now(); // 存储当前时间的毫秒级时间戳 int timestamp = now.millisecondsSinceEpoch; final db = await SQLHelper.db(); //opening the database final data = { 'exercise_name': exercise_name, 'total_weight': total_weight, 'total_reps': total_reps, 'timestamp': timestamp, // 替换原date字段,或新增该字段 'is_favorite': 0 }; final id = await db.insert( 'sets', data, conflictAlgorithm: sql.ConflictAlgorithm.replace); return id; }
方案B:存储带时分秒的ISO格式字符串
如果需要保留可读的日期字符串,改用yyyy-MM-dd HH:mm:ss格式:
//method to create an item to insert into the database table static Future<int> createItem( String exercise_name, String? total_weight, String? total_reps, ) async { DateTime now = DateTime.now(); // 存储带时分秒的标准格式日期字符串 String formattedDate = DateFormat('yyyy-MM-dd HH:mm:ss').format(now); final db = await SQLHelper.db(); //opening the database final data = { 'exercise_name': exercise_name, 'total_weight': total_weight, 'total_reps': total_reps, 'date': formattedDate, 'is_favorite': 0 }; final id = await db.insert( 'sets', data, conflictAlgorithm: sql.ConflictAlgorithm.replace); return id; }
步骤2:修改getItems函数筛选最近24小时记录
对应方案A(时间戳)的查询逻辑
static Future<List<Map<String, dynamic>>> getItems() async { final db = await SQLHelper.db(); // 计算24小时前的毫秒级时间戳 int twentyFourHoursAgo = DateTime.now().subtract(const Duration(hours: 24)).millisecondsSinceEpoch; return db.query( 'sets', where: "timestamp >= ?", whereArgs: [twentyFourHoursAgo], orderBy: "timestamp DESC" // 按时间倒序,最新记录在前 ); }
对应方案B(ISO字符串)的查询逻辑
static Future<List<Map<String, dynamic>>> getItems() async { final db = await SQLHelper.db(); // 计算24小时前的ISO格式日期字符串 String twentyFourHoursAgoStr = DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now().subtract(const Duration(hours: 24))); return db.query( 'sets', where: "date >= ?", whereArgs: [twentyFourHoursAgoStr], orderBy: "date DESC" ); }
注意事项
如果数据库已有旧数据,需要执行表结构迁移:
- 若用方案A,需给
sets表新增timestamp字段,并批量更新旧记录的timestamp值(根据原date字段转换) - 若用方案B,需批量更新旧记录的
date字段,补充时分秒(可设为当天00:00:00)
内容的提问来源于stack exchange,提问作者user21233522
相关产品推荐
相关产品推荐

