82 lines
2.3 KiB
Dart
82 lines
2.3 KiB
Dart
/// 格式化时间
|
||
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]: 秒数
|
||
/// - [format]: 格式化字符串,默认为 "hh:mm:ss"
|
||
String formatSeconds(
|
||
int seconds, [
|
||
String format = 'hh:mm:ss',
|
||
]) {
|
||
if (seconds < 0) seconds = 0;
|
||
|
||
int h = seconds ~/ 3600;
|
||
int m = (seconds % 3600) ~/ 60;
|
||
int s = seconds % 60;
|
||
|
||
String two(int n) => n.toString().padLeft(2, '0');
|
||
|
||
// 支持以下 token:
|
||
// hh = 补零小时, h = 不补零小时
|
||
// mm = 补零分钟, m = 不补零分钟
|
||
// ss = 补零秒, s = 不补零秒
|
||
final replacements = {
|
||
'hh': two(h),
|
||
'mm': two(m),
|
||
'ss': two(s),
|
||
'h': h.toString(),
|
||
'm': m.toString(),
|
||
's': s.toString(),
|
||
};
|
||
|
||
String result = format;
|
||
|
||
replacements.forEach((key, value) {
|
||
result = result.replaceAll(key, value);
|
||
});
|
||
|
||
return result;
|
||
}
|
||
|
||
/// 将 "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);
|
||
}
|