You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

30 lines
1.1 KiB

  1. function timeFormat(timestamp = null, fmt = 'yyyy-mm-dd') {
  2. // 其他更多是格式化有如下:
  3. // yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合
  4. timestamp = parseInt(timestamp);
  5. // 如果为null,则格式化当前时间
  6. if (!timestamp) timestamp = Number(new Date());
  7. // 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
  8. if (timestamp.toString().length == 10) timestamp *= 1000;
  9. let date = new Date(timestamp);
  10. let ret;
  11. let opt = {
  12. "y+": date.getFullYear().toString(), // 年
  13. "m+": (date.getMonth() + 1).toString(), // 月
  14. "d+": date.getDate().toString(), // 日
  15. "h+": date.getHours().toString(), // 时
  16. "M+": date.getMinutes().toString(), // 分
  17. "s+": date.getSeconds().toString() // 秒
  18. // 有其他格式化字符需求可以继续添加,必须转化成字符串
  19. };
  20. for (let k in opt) {
  21. ret = new RegExp("(" + k + ")").exec(fmt);
  22. if (ret) {
  23. fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
  24. };
  25. };
  26. return fmt;
  27. }
  28. export default timeFormat