util.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. function friendlyDate(timestamp) {
  2. var formats = {
  3. 'year': '%n% 年前',
  4. 'month': '%n% 月前',
  5. 'day': '%n% 天前',
  6. 'hour': '%n% 小时前',
  7. 'minute': '%n% 分钟前',
  8. 'second': '%n% 秒前',
  9. };
  10. var now = Date.now();
  11. var seconds = Math.floor((now - timestamp) / 1000);
  12. var minutes = Math.floor(seconds / 60);
  13. var hours = Math.floor(minutes / 60);
  14. var days = Math.floor(hours / 24);
  15. var months = Math.floor(days / 30);
  16. var years = Math.floor(months / 12);
  17. var diffType = '';
  18. var diffValue = 0;
  19. if (years > 0) {
  20. diffType = 'year';
  21. diffValue = years;
  22. } else {
  23. if (months > 0) {
  24. diffType = 'month';
  25. diffValue = months;
  26. } else {
  27. if (days > 0) {
  28. diffType = 'day';
  29. diffValue = days;
  30. } else {
  31. if (hours > 0) {
  32. diffType = 'hour';
  33. diffValue = hours;
  34. } else {
  35. if (minutes > 0) {
  36. diffType = 'minute';
  37. diffValue = minutes;
  38. } else {
  39. diffType = 'second';
  40. diffValue = seconds === 0 ? (seconds = 1) : seconds;
  41. }
  42. }
  43. }
  44. }
  45. }
  46. return formats[diffType].replace('%n%', diffValue);
  47. }
  48. function getStorage(key) {
  49. //#ifdef H5
  50. const value = localStorage.getItem(key);
  51. return value !== null && value !== undefined ? value : undefined;
  52. //#endif
  53. //#ifndef H5
  54. const value = uni.getStorageSync(key);
  55. return value !== null && value !== undefined ? value : undefined;
  56. //#endif
  57. }
  58. function setStorage(key, value) {
  59. //#ifdef H5
  60. localStorage.setItem(key, value);
  61. //#endif
  62. //#ifndef H5
  63. return uni.setStorageSync(key, value);
  64. //#endif
  65. }
  66. function removeStorage(key) {
  67. //#ifdef H5
  68. localStorage.removeItem(key);
  69. //#endif
  70. //#ifndef H5
  71. return uni.removeStorageSync(key);
  72. //#endif
  73. }
  74. export {
  75. friendlyDate,
  76. getStorage,
  77. setStorage,
  78. removeStorage
  79. }