time.js 1.7 KB

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