time.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. function commentTimeHandle(dateStr) {
  2. // dateStr = 2018-09-06 18:47:00" 测试时间
  3. var publishTime = dateStr / 1000, //获取dataStr的秒数 打印结果--1536230820000
  4. date = new Date(publishTime * 1000), //获取dateStr的标准格式 console.log(date) 打印结果 Thu Sep 06 2018 18:47:00 GMT+0800 (中国标准时间)
  5. // 获取date 中的 年 月 日 时 分 秒
  6. Y = date.getFullYear(),
  7. M = date.getMonth() + 1,
  8. D = date.getDate(),
  9. H = date.getHours(),
  10. m = date.getMinutes(),
  11. s = date.getSeconds();
  12. // 对 月 日 时 分 秒 小于10时, 加0显示 例如: 09-09 09:01
  13. if (M < 10) {
  14. M = '0' + M;
  15. }
  16. if (D < 10) {
  17. D = '0' + D;
  18. }
  19. if (H < 10) {
  20. H = '0' + H;
  21. }
  22. if (m < 10) {
  23. m = '0' + m;
  24. }
  25. if (s < 10) {
  26. s = '0' + s;
  27. }
  28. // console.log("年", Y); // 年 2018
  29. // console.log("月", M); // 月 09
  30. // console.log("日", D); // 日 06
  31. // console.log("时", H); // 时 18
  32. // console.log("分", m); // 分 47
  33. // console.log("秒", s); // 秒 00
  34. var nowTime = new Date().getTime() / 1000, //获取此时此刻日期的秒数
  35. diffValue = nowTime - publishTime, // 获取此时 秒数 与 要处理的日期秒数 之间的差值
  36. diff_days = parseInt(diffValue / 86400), // 一天86400秒 获取相差的天数 取整
  37. diff_hours = parseInt(diffValue / 3600), // 一时3600秒
  38. diff_minutes = parseInt(diffValue / 60),
  39. diff_secodes = parseInt(diffValue);
  40. if (diff_days > 0 && diff_days < 3) { //相差天数 0 < diff_days < 3 时, 直接返出
  41. return diff_days + "天前";
  42. } else if (diff_days <= 0 && diff_hours > 0) {
  43. return diff_hours + "小时前";
  44. } else if (diff_hours <= 0 && diff_minutes > 0) {
  45. return diff_minutes + "分钟前";
  46. } else if (diff_secodes < 60) {
  47. if (diff_secodes <= 0) {
  48. return "刚刚";
  49. } else {
  50. return diff_secodes + "秒前";
  51. }
  52. } else if (diff_days >= 3 && diff_days < 30) {
  53. return M + '-' + D + ' ' + H + ':' + m;
  54. } else if (diff_days >= 30) {
  55. return Y + '-' + M + '-' + D + ' ' + H + ':' + m;
  56. }
  57. }
  58. module.exports = {
  59. timeHandle: commentTimeHandle
  60. }