DateFormat.dart 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 formatCreateAtHHmm(String date) {
  13. if(date == null)
  14. return '';
  15. var time =DateTime.parse(date);
  16. return "${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}";
  17. }
  18. static String formatCreateAt(String date) {
  19. if(date == null)
  20. return '';
  21. return format(DateTime.parse(date));
  22. }
  23. static String format(DateTime date) {
  24. return formatTime(date.millisecondsSinceEpoch ~/ 1000);
  25. }
  26. static String formatTime(num time) {
  27. num delta = DateTime.now().millisecondsSinceEpoch - time * 1000;
  28. if(delta<=1000){
  29. return "刚刚";
  30. }
  31. if (delta < 1 * ONE_MINUTE) {
  32. num seconds = toSeconds(delta);
  33. return (seconds <= 0 ? 1 : seconds).toInt().toString() + ONE_SECOND_AGO;
  34. }
  35. if (delta < 60 * ONE_MINUTE) {
  36. num minutes = toMinutes(delta);
  37. return (minutes <= 0 ? 1 : minutes).toInt().toString() + ONE_MINUTE_AGO;
  38. }
  39. if (delta < 24 * ONE_HOUR) {
  40. num hours = toHours(delta);
  41. return (hours <= 0 ? 1 : hours).toInt().toString() + ONE_HOUR_AGO;
  42. }
  43. var date = DateTime.fromMillisecondsSinceEpoch(time * 1000);
  44. return "${date.year}-${date.month}-${date.day}";
  45. // if (delta < 48 * ONE_HOUR) {
  46. // return "昨天";
  47. // }
  48. // if (delta < 30 * ONE_DAY) {
  49. // num days = toDays(delta);
  50. // return (days <= 0 ? 1 : days).toInt().toString() + ONE_DAY_AGO;
  51. // }
  52. // if (delta < 12 * 4 * ONE_WEEK) {
  53. // num months = toMonths(delta);
  54. // return (months <= 0 ? 1 : months).toInt().toString() + ONE_MONTH_AGO;
  55. // } else {
  56. // num years = toYears(delta);
  57. // return (years <= 0 ? 1 : years).toInt().toString() + ONE_YEAR_AGO;
  58. // }
  59. }
  60. static num toSeconds(num date) {
  61. return date / 1000;
  62. }
  63. static num toMinutes(num date) {
  64. return toSeconds(date) / 60;
  65. }
  66. static num toHours(num date) {
  67. return toMinutes(date) / 60;
  68. }
  69. static num toDays(num date) {
  70. return toHours(date) / 24;
  71. }
  72. static num toMonths(num date) {
  73. return toDays(date) / 30;
  74. }
  75. static num toYears(num date) {
  76. return toMonths(date) / 365;
  77. }
  78. }