date.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233
  1. export function formatDateTime(date:any) {
  2. const year = date.getFullYear(); // 获取年份
  3. const month = String(date.getMonth() + 1).padStart(2, '0'); // 获取月份
  4. const day = String(date.getDate()).padStart(2, '0'); // 获取日期
  5. const hours = String(date.getHours()).padStart(2, '0'); // 获取小时
  6. const minutes = String(date.getMinutes()).padStart(2, '0'); // 获取分钟
  7. const seconds = String(date.getSeconds()).padStart(2, '0'); // 获取秒钟
  8. return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  9. }
  10. /*
  11. *计算时间与当前的小时
  12. */
  13. export function getTimeHours(date: Date | string): number | undefined {
  14. if (!date) return undefined;
  15. const targetTime = new Date(date);
  16. if (isNaN(targetTime.getTime())) return undefined; // 检查日期是否有效
  17. const currentTime = new Date();
  18. const timeDiff = currentTime.getTime() - targetTime.getTime(); // 获取毫秒差
  19. return Math.floor(timeDiff / (1000 * 60 * 60)); // 转换为小时
  20. }
  21. /*
  22. *获取当前时间时分秒
  23. */
  24. export function getCurrentTime() {
  25. const now = new Date();
  26. const hours = String(now.getHours()).padStart(2, '0');
  27. const minutes = String(now.getMinutes()).padStart(2, '0');
  28. const seconds = String(now.getSeconds()).padStart(2, '0');
  29. return `${hours}:${minutes}:${seconds}`;
  30. };