阅读量:0
因为日期、时间格式化在项目里面用得比较多,所以一般封装成一个方法,放在utils文件夹了,所以我先建了一个utils文件夹,然后新建一个文件叫做tools.dart。
class Tools { static formatTime(timeStamp, {format = '{y}-{m}-{d} {h}:{i}:{s}'}) { if(timeStamp == null) return null; if ('$timeStamp'.length == 10) { timeStamp *= 1000; } DateTime date = DateTime.fromMillisecondsSinceEpoch(timeStamp); var formatObj = { 'y': date.year, 'm': date.month, 'd': date.day, 'h': date.hour, 'i': date.minute, 's': date.second, 'a': date.weekday, }; RegExp exp = RegExp("{(y|m|d|h|i|s|a)+}"); var timeStr = format.replaceAllMapped(exp, (Match match) { var result = match.group(0); // {m} var key = match.group(1); // m var value = formatObj[key]; if (key == 'a') return ['一', '二', '三', '四', '五', '六', '日'][value! - 1]; var s = '$value'; if (result!.isNotEmpty && value! < 10) { s = '0$value'; } return s; }); return timeStr; } static getWeek(timeStamp) { if(timeStamp == null) return null; String week = ''; if ('$timeStamp'.length == 10) { timeStamp *= 1000; } DateTime date = DateTime.fromMillisecondsSinceEpoch(timeStamp); if (date.weekday == 0) week = "星期日"; if (date.weekday == 1) week = "星期一"; if (date.weekday == 2) week = "星期二"; if (date.weekday == 3) week = "星期三"; if (date.weekday == 4) week = "星期四"; if (date.weekday == 5) week = "星期五"; if (date.weekday == 6) week = "星期六"; return week; } }