/// 格式化时间 String formatDate(dynamic date, [String format = 'YYYY-MM-DD hh:mm:ss']) { DateTime dateTime; if (date is String) { // 如果是字符串类型,尝试将其解析为 DateTime dateTime = DateTime.tryParse(date) ?? DateTime.now(); } else if (date is DateTime) { // 如果是 DateTime 类型,直接使用 dateTime = date; } else { // 如果不是合法的输入类型,默认使用当前时间 dateTime = DateTime.now(); } final yyyy = dateTime.year.toString(); final MM = (dateTime.month).toString().padLeft(2, '0'); final dd = (dateTime.day).toString().padLeft(2, '0'); final HH = (dateTime.hour).toString().padLeft(2, '0'); final mm = (dateTime.minute).toString().padLeft(2, '0'); final ss = (dateTime.second).toString().padLeft(2, '0'); String result = format .replaceFirst(RegExp('YYYY'), '$yyyy') .replaceFirst(RegExp('MM'), MM) .replaceFirst(RegExp('DD'), dd) .replaceFirst(RegExp('hh'), HH) .replaceFirst(RegExp('mm'), mm) .replaceFirst(RegExp('ss'), ss); return result; } /// 将秒数格式化为 00:00 或 00:00:00 /// - [seconds]: 秒数 String formatSeconds(int seconds) { final h = seconds ~/ 3600; final m = (seconds % 3600) ~/ 60; final s = seconds % 60; String twoDigits(int n) => n.toString().padLeft(2, '0'); if (h > 0) { return '${twoDigits(h)}:${twoDigits(m)}:${twoDigits(s)}'; } else { return '${twoDigits(m)}:${twoDigits(s)}'; } } /// 将 "HH", "HH:mm" 或 "HH:mm:ss" 转为当天 DateTime DateTime parseTime(String timeStr) { final now = DateTime.now(); final parts = timeStr.split(':').map(int.parse).toList(); final hour = parts.length > 0 ? parts[0] : 0; final minute = parts.length > 1 ? parts[1] : 0; final second = parts.length > 2 ? parts[2] : 0; return DateTime(now.year, now.month, now.day, hour, minute, second); }