time.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /**
  2. * 时间戳转时间字符串
  3. * @param timestamp
  4. * @returns {string}
  5. */
  6. export function timestampToTime(timestamp) {
  7. timestamp = timestamp.toString().length === 10 ? timestamp * 1000 : timestamp;
  8. let date = new Date(timestamp); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
  9. let Y = date.getFullYear() + '-';
  10. let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
  11. let D = date.getDate() + ' ';
  12. let h = date.getHours() + ':';
  13. let m = date.getMinutes() + ':';
  14. let s = date.getSeconds();
  15. return Y+M+D+h+m+s;
  16. }
  17. /**
  18. * 时间字符串转时间戳
  19. * @param timeStr
  20. * @param isSecond
  21. * @returns {number}
  22. */
  23. export function timeStrToTimeStamp(timeStr,isSecond){
  24. let date = new Date(timeStr);
  25. if(isSecond){
  26. return date.getTime()/1000;
  27. }else{
  28. return date.getTime();
  29. }
  30. }
  31. /**
  32. * 时间戳转时间字符串
  33. * @param time 时间戳
  34. * @param format 格式 yyyy-MM-dd HH:mm:ss
  35. * @returns {*} 格式化后的时间字符串
  36. */
  37. export function timeFormat(time, format) {
  38. let t = new Date(time);
  39. let tf = function(i) {
  40. return (i < 10 ? '0' : '') + i
  41. };
  42. return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a) {
  43. switch (a) {
  44. case 'yyyy':
  45. return tf(t.getFullYear());
  46. break;
  47. case 'MM':
  48. return tf(t.getMonth() + 1);
  49. break;
  50. case 'mm':
  51. return tf(t.getMinutes());
  52. break;
  53. case 'dd':
  54. return tf(t.getDate());
  55. break;
  56. case 'HH':
  57. return tf(t.getHours());
  58. break;
  59. case 'ss':
  60. return tf(t.getSeconds());
  61. break;
  62. }
  63. })
  64. }