DateFormat.dart 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. class DateFormat {
  2. static const num ONE_MINUTE = 60000;
  3. static const num ONE_HOUR = 3600000;
  4. static const num ONE_DAY = 86400000;
  5. static const num ONE_WEEK = 604800000;
  6. static const String ONE_SECOND_AGO = "秒前";
  7. static const String ONE_MINUTE_AGO = "分钟前";
  8. static const String ONE_HOUR_AGO = "小时前";
  9. static const String ONE_DAY_AGO = "天前";
  10. static const String ONE_MONTH_AGO = "月前";
  11. static const String ONE_YEAR_AGO = "年前";
  12. static String formatCreateAt(String date) {
  13. if(date == null)
  14. return '';
  15. return format(DateTime.parse(date));
  16. }
  17. static String format(DateTime date) {
  18. return formatTime(date.millisecondsSinceEpoch ~/ 1000);
  19. }
  20. static String formatTime(num time) {
  21. num delta = DateTime.now().millisecondsSinceEpoch - time * 1000;
  22. if(delta<=1000){
  23. return "刚刚";
  24. }
  25. if (delta < 1 * ONE_MINUTE) {
  26. num seconds = toSeconds(delta);
  27. return (seconds <= 0 ? 1 : seconds).toInt().toString() + ONE_SECOND_AGO;
  28. }
  29. if (delta < 60 * ONE_MINUTE) {
  30. num minutes = toMinutes(delta);
  31. return (minutes <= 0 ? 1 : minutes).toInt().toString() + ONE_MINUTE_AGO;
  32. }
  33. if (delta < 24 * ONE_HOUR) {
  34. num hours = toHours(delta);
  35. return (hours <= 0 ? 1 : hours).toInt().toString() + ONE_HOUR_AGO;
  36. }
  37. var date = DateTime.fromMillisecondsSinceEpoch(time * 1000);
  38. return "${date.year}-${date.month}-${date.day}";
  39. // if (delta < 48 * ONE_HOUR) {
  40. // return "昨天";
  41. // }
  42. // if (delta < 30 * ONE_DAY) {
  43. // num days = toDays(delta);
  44. // return (days <= 0 ? 1 : days).toInt().toString() + ONE_DAY_AGO;
  45. // }
  46. // if (delta < 12 * 4 * ONE_WEEK) {
  47. // num months = toMonths(delta);
  48. // return (months <= 0 ? 1 : months).toInt().toString() + ONE_MONTH_AGO;
  49. // } else {
  50. // num years = toYears(delta);
  51. // return (years <= 0 ? 1 : years).toInt().toString() + ONE_YEAR_AGO;
  52. // }
  53. }
  54. static num toSeconds(num date) {
  55. return date / 1000;
  56. }
  57. static num toMinutes(num date) {
  58. return toSeconds(date) / 60;
  59. }
  60. static num toHours(num date) {
  61. return toMinutes(date) / 60;
  62. }
  63. static num toDays(num date) {
  64. return toHours(date) / 24;
  65. }
  66. static num toMonths(num date) {
  67. return toDays(date) / 30;
  68. }
  69. static num toYears(num date) {
  70. return toMonths(date) / 365;
  71. }
  72. }