formatter.js 832 B

1234567891011121314151617181920212223242526
  1. export const formatTime = (t, format) => {
  2. if (typeof t === 'number' || typeof t === 'string') {
  3. t = new Date(t);
  4. }
  5. if (!(t instanceof Date)) {
  6. return null;
  7. }
  8. const o = {
  9. 'M+': t.getMonth() + 1,
  10. 'd+': t.getDate(),
  11. 'h+': t.getHours(),
  12. 'm+': t.getMinutes(),
  13. 's+': t.getSeconds(),
  14. 'q+': Math.floor((t.getMonth() + 3) / 3),
  15. 'S': t.getMilliseconds() // millisecond
  16. };
  17. if (/(y+)/.test(format)) {
  18. format = format.replace(RegExp.$1, (t.getFullYear() + '').substr(4 - RegExp.$1.length));
  19. }
  20. for (const k in o) {
  21. if (new RegExp('(' + k + ')').test(format)) {
  22. format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
  23. }
  24. }
  25. return format;
  26. };