TimeUtil.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // 根据时间戳格式化时间为**分钟前,**天前这种格式
  2. function getFormattedTime(timestamp) {
  3. let curTime = Date.parse(new Date()) / 1000;
  4. let delta = curTime - timestamp;
  5. const hour = 60 * 60;
  6. const day = 24 * hour;
  7. const month = 30 * day;
  8. const year = 12 * month;
  9. if (delta < hour) {
  10. // 显示多少分钟前
  11. let n = parseInt(delta / 60);
  12. if (n == 0) {
  13. return "刚刚";
  14. }
  15. return n + '分钟前';
  16. } else if (delta >= hour && delta < day) {
  17. return parseInt(delta / hour) + '小时前';
  18. } else if (delta >= day && delta < month) {
  19. return parseInt(delta / day) + '天前';
  20. } else if (delta >= month && delta < year) {
  21. return parseInt(delta / month) + '个月前';
  22. }
  23. }
  24. function format(date, fmt) {
  25. var o = {
  26. "M+": date.getMonth() + 1, //月份
  27. "d+": date.getDate(), //日
  28. "h+": date.getHours(), //小时
  29. "m+": date.getMinutes(), //分
  30. "s+": date.getSeconds(), //秒
  31. "q+": Math.floor((date.getMonth() + 3) / 3), //季度
  32. "S": date.getMilliseconds() //毫秒
  33. };
  34. if (/(y+)/.test(fmt)) {
  35. fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  36. }
  37. for (var k in o) {
  38. if (new RegExp("(" + k + ")").test(fmt)) {
  39. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  40. }
  41. }
  42. return fmt;
  43. }
  44. function formatChatTime(timestamp) {
  45. return format(new Date(timestamp * 1000), 'MM月dd日 hh:mm');
  46. }
  47. function currentTime() {
  48. return Date.parse(new Date()) / 1000;
  49. }
  50. module.exports = {
  51. getFormattedTime: getFormattedTime,
  52. formatChatTime: formatChatTime,
  53. currentTime: currentTime
  54. }