index.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /**
  2. * Created by jiachenpan on 16/11/18.
  3. */
  4. export function parseTime(time, cFormat) {
  5. if (arguments.length === 0) {
  6. return null;
  7. }
  8. const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
  9. let date;
  10. if (typeof time == 'object') {
  11. date = time;
  12. } else {
  13. if (('' + time).length === 10) time = parseInt(time) * 1000;
  14. date = new Date(time);
  15. }
  16. const formatObj = {
  17. y: date.getFullYear(),
  18. m: date.getMonth() + 1,
  19. d: date.getDate(),
  20. h: date.getHours(),
  21. i: date.getMinutes(),
  22. s: date.getSeconds(),
  23. a: date.getDay()
  24. };
  25. const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
  26. let value = formatObj[key];
  27. if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1];
  28. if (result.length > 0 && value < 10) {
  29. value = '0' + value;
  30. }
  31. return value || 0;
  32. });
  33. return time_str;
  34. }
  35. export function formatTime(time, option) {
  36. time = +time * 1000;
  37. const d = new Date(time);
  38. const now = Date.now();
  39. const diff = (now - d) / 1000;
  40. if (diff < 30) {
  41. return '刚刚'
  42. } else if (diff < 3600) { // less 1 hour
  43. return Math.ceil(diff / 60) + '分钟前'
  44. } else if (diff < 3600 * 24) {
  45. return Math.ceil(diff / 3600) + '小时前'
  46. } else if (diff < 3600 * 24 * 2) {
  47. return '1天前'
  48. }
  49. if (option) {
  50. return parseTime(time, option)
  51. } else {
  52. return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  53. }
  54. }