time.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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
  43. .replace(/yyyy/,tf(t.getFullYear()))
  44. .replace(/MM/,tf(t.getMonth() + 1))
  45. .replace(/M/,String(t.getMonth() + 1))
  46. .replace(/dd/,tf(t.getDate()))
  47. .replace(/d/,String(t.getDate()))
  48. .replace(/HH/,tf(t.getHours()))
  49. .replace(/H/,String(t.getHours()))
  50. .replace(/mm/,tf(t.getMinutes()))
  51. .replace(/m/,String(t.getMinutes()))
  52. .replace(/ss/,tf(t.getSeconds()))
  53. .replace(/s/,String(t.getSeconds()));
  54. }
  55. export function getUnixTimeStamp(){
  56. return Math.round(new Date().getTime()/1000);
  57. }