带你读《现代Javascript高级教程》二十三、Date类:日期和时间处理(1)https://developer.aliyun.com/article/1349522?groupCode=tech_library
b) 实现toISODate方法
Date.prototype.toISODate = function() { const year = this.getFullYear(); const month = String(this.getMonth() + 1).padStart(2, '0'); const day = String(this.getDate()).padStart(2, '0'); return `year−{year}-{month}-${day}`;}; // 使用示例const date = new Date();const isoDate = date.toISODate(); console.log(isoDate);
2) 计算两个日期之间的天数差
Date.prototype.getDaysDiff = function(otherDate) { const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数 const diffInTime = Math.abs(this - otherDate); const diffInDays = Math.round(diffInTime / oneDay); return diffInDays;}; // 使用示例const date1 = new Date('2022-01-01');const date2 = new Date('2022-01-10');const daysDiff = date1.getDaysDiff(date2); console.log(daysDiff); // 输出 9
3) 获取当前月份的第一天和最后一天
Date.prototype.getFirstDayOfMonth = function() { const year = this.getFullYear(); const month = this.getMonth(); return new Date(year, month, 1);}; Date.prototype.getLastDayOfMonth = function() { const year = this.getFullYear(); const month = this.getMonth() + 1; return new Date(year, month, 0);}; // 使用示例const date = new Date();const firstDayOfMonth = date.getFirstDayOfMonth();const lastDayOfMonth = date.getLastDayOfMonth(); console.log(firstDayOfMonth); console.log(lastDayOfMonth);
- 总结
本文介绍了Date类的属性、应用场景,并提供了一些常用的Date方法的实现代码示例。Date类在JavaScript中用于处理日期和时间相关的操作非常重要,掌握其基本用法能够帮助我们更好地处理和管理日期和时间。通过逐步学习和实践,我们可以在实际项目中灵活运用Date类,满足各种日期和时间处理的需求。
- 参考资料
- MDN Web Docs: Dateopen in new window
- JavaScript Date Objectopen in new window
- ECMAScript® 2021 Language Specification - Date Objects