getFormattedDate 函数:简化 JavaScript 和 TypeScript 日期格式化
此 JavaScript/TypeScript 函数 getFormattedDate 简化了日期格式化,提供多种格式选项,确保可靠的日期转换。支持多种日期格式,包括 dd/MM/yyyy、MM/dd/yyyy、yyyy/MM/dd 和 yyyy/dd/MM,并提供完整的日期显示格式(例如,“2024年10月15日”),增强可读性。
import { allMonths } from "@/constants/months.constants"; export const getFormattedDate = ( date: string | Date, format?: "dd/MM/yyyy" | "MM/dd/yyyy" | "yyyy/MM/dd" | "yyyy/dd/MM", fullDate: boolean = false ): string => { const dateObj = typeof date === "string" ? new Date(date) : date; if (isNaN(dateObj.getTime())) { throw new Error("无效日期"); } const day = dateObj.getDate().toString().padStart(2, "0"); const month = (dateObj.getMonth() + 1).toString().padStart(2, "0"); const year = dateObj.getFullYear(); if (fullDate) { return `${day} ${allMonths[dateObj.getMonth()]} ${year}`; } switch (format) { case "dd/MM/yyyy": return `${day}/${month}/${year}`; case "MM/dd/yyyy": return `${month}/${day}/${year}`; case "yyyy/MM/dd": return `${year}/${month}/${day}`; case "yyyy/dd/MM": return `${year}/${day}/${month}`; default: throw new Error("不支持的格式"); } }; const exampleDate = "2024-02-10T12:30:00Z"; getFormattedDate(exampleDate, "dd/MM/yyyy"); // 使用 fullDate: true 获取完整日期格式
主要功能:
适用场景:
立即学习“Java免费学习笔记(深入)”;
该实用程序非常适合电子商务平台、预订系统、博客和仪表板等需要日期显示的应用场景,它能优化日期显示,同时保持代码简洁高效。
感谢 Ancliful Islam 的贡献,其代码编写清晰易懂。
以上就是JavaScript日期实用程序:转换,格式和显示日期的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号