date.ts 758 B

1234567891011121314151617181920
  1. export function format(format: string, time?: number) {
  2. const now = time ? new Date(time) : new Date();
  3. const map: Record<string, string | number> = {
  4. y: now.getFullYear(),
  5. M: now.getMonth() + 1 > 9 ? now.getMonth() + 1 : `0${now.getMonth() + 1}`,
  6. d: now.getDate() > 9 ? now.getDate() : `0${now.getDate()}`,
  7. h: now.getHours() > 9 ? now.getHours() : `0${now.getHours()}`,
  8. m: now.getMinutes() > 9 ? now.getMinutes() : `0${now.getMinutes()}`,
  9. s: now.getSeconds() > 9 ? now.getSeconds() : `0${now.getSeconds()}`,
  10. };
  11. const res = [];
  12. for (let i = 0; i < format.length; i++) {
  13. if (map[format.charAt(i)]) {
  14. res.push(map[format.charAt(i)]);
  15. } else {
  16. res.push(format.charAt(i));
  17. }
  18. }
  19. return res.join("");
  20. }