flutter开发实战-时间显示刚刚几分钟前几小时前
在开发中经常遇到从服务端获取的时间戳,需要转换显示刚刚、几分钟前、几小时前、几天前、年月日等格式。
一、代码实现
static String timeFormatterChatTimeStamp(int seconds) {
try {
int nowDateSeconds =
(DateTime.now().millisecondsSinceEpoch / 1000).truncate();
String anotherDate =
DateUtil.formatDateMs(seconds*1000, format: DateFormats.full);
String nowDate =
DateUtil.formatDateMs(nowDateSeconds*1000, format: DateFormats.full);
print(
"timeFormatterChatTimeStamp "
"seconds:${seconds},"
"nowDateSeconds:${nowDateSeconds},"
"anotherDate:${anotherDate},"
"nowDate:${nowDate}");
//为了判断当前时间是否为未来时间
if (seconds > nowDateSeconds) {
return anotherDate;
}
List<String> anotherDateList = anotherDate.split(" ");
List<String> nowDateList = nowDate.split(" ");
if (anotherDateList.length == 2 && nowDateList.length == 2) {
String nowDateYMD = nowDateList[0];
String nowDateHMS = nowDateList[1];
String anotherDateYMD = anotherDateList[0];
String anotherDateHMS = anotherDateList[1];
List<String> anotherDateYMDList = anotherDateYMD.split("-");
List<String> nowDateYMDList = nowDateYMD.split("-");
List<String> anotherDateHMSList = anotherDateHMS.split(":");
List<String> nowDateHMSList = nowDateHMS.split(":");
String anotherDateY = anotherDateYMDList[0];
String anotherDateM = anotherDateYMDList[1];
String anotherDateD = anotherDateYMDList[2];
String nowDateY = nowDateYMDList[0];
String nowDateM = nowDateYMDList[1];
String nowDateD = nowDateYMDList[2];
String anotherDateH = anotherDateHMSList[0];
String anotherDateMi = anotherDateHMSList[1];
String anotherDateS = anotherDateHMSList[2];
int year = int.parse(anotherDateY) - int.parse(nowDateY);
if (year < 0) {
// 过去(今年以前)
return "${anotherDateY}年${anotherDateM}月${anotherDateD}日 ${anotherDateH}:${anotherDateMi}";
} else {
if (nowDateY == anotherDateY) {
// 今年
return "${anotherDateM}月${anotherDateD}日 ${anotherDateH}:${anotherDateMi}";
} else {
return "${anotherDateY}年${anotherDateM}月${anotherDateD}日 ${anotherDateH}:${anotherDateMi}";
}
}
} else {
return anotherDate;
}
} catch (e) {
return "${seconds}";
}
}
二、小结
flutter开发实战-格式化时间显示刚刚几分钟前几小时前等
从服务端获取的时间戳,需要转换显示刚刚、几分钟前、几小时前、几天前、年月日等格式。用到了DateUtil。文章来源:https://www.toymoban.com/news/detail-633764.html
学习记录,每天不停进步。文章来源地址https://www.toymoban.com/news/detail-633764.html
到了这里,关于flutter开发实战-时间显示刚刚几分钟前几小时前的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!