new DateTime.now();
new DateTime(2020, 11, 11, 12, 37 , 36);
DateTime.parse('2018-10-10 09:30:36');
// 加10分鐘 now.add(new Duration(minutes: 10)) // 減2小時 now.add(new Duration(hours: -2))
var d3 = new DateTime(2019, 6, 20); var d4 = new DateTime(2019, 7, 20); var d5 = new DateTime(2019, 6, 20); print(d3.isAfter(d4));//是否在d4以後 false print(d3.isBefore(d4));//是否在d4以前 true print(d3.isAtSameMomentAs(d5));//是否相同 true
var d6 = new DateTime(2019, 6, 19, 16 , 30); var d7 = new DateTime(2019, 6, 20, 15, 20); var difference = d7.difference(d6); print([difference.inDays, difference.inHours,difference.inMinutes]);//d6與d7相差的天數與小時,分鐘 [0, 22, 1370]
print(now.millisecondsSinceEpoch);//單位毫秒,13位時間戳 1561021145560 print(now.microsecondsSinceEpoch);//單位微秒,16位時間戳 1561021145560543
目標:輸出發佈時間this
規則:小於一分鐘,輸出‘剛剛’;小於一小時,輸出‘xx分鐘前’;小於一天,輸出‘xx小時前’;小於三天,輸出‘xx天前’;大於三天,且在本年度內,輸出‘xx月xx日’;大於三天,但不在本年度內,輸出‘xx年xx月xx日’。spa
思路:先保證時間戳正確,而後比較當前時間和發佈時間。code
代碼:orm
String get publishTime { var now = new DateTime.now(); var longTime = this.toString().length < 13 ? this * 1000 : this; var time = new DateTime.fromMillisecondsSinceEpoch(longTime); var difference = now.difference(time); int days = difference.inDays; int hours = difference.inHours; int minutes = difference.inMinutes; String result = ''; if (days > 3) { bool isNowYear = now.year == time.year; var pattern = isNowYear ? 'MM-dd' : 'yyyy-MM-dd'; result = new DateFormat(pattern).format(time); } else if (days > 0) { result = '$days天前'; } else if (hours > 0) { result = '$hours小時前'; } else if (minutes > 0) { result = '$minutes分鐘前'; } else { result = '剛剛'; } return result; }
END---------------blog