js date(长文解析)

更新时间:

💡一则或许对你有用的小广告

欢迎加入小哈的星球 ,你将获得:专属的项目实战 / 1v1 提问 / Java 学习路线 / 学习打卡 / 每月赠书 / 社群讨论

截止目前, 星球 内专栏累计输出 90w+ 字,讲解图 3441+ 张,还在持续爆肝中.. 后续还会上新更多项目,目标是将 Java 领域典型的项目都整一波,如秒杀系统, 在线商城, IM 即时通讯,权限管理,Spring Cloud Alibaba 微服务等等,已有 3100+ 小伙伴加入学习 ,欢迎点击围观

在 JavaScript 开发中,日期和时间的处理是一个高频且复杂的场景。无论是构建日历应用、计算用户年龄,还是实现倒计时功能,开发者都需要与 Date 对象打交道。本文将围绕 js date 核心知识点展开,从基础语法到进阶技巧,结合代码案例和常见陷阱,帮助编程初学者和中级开发者系统掌握这一工具。


一、Date 对象:JavaScript 的时间管家

JavaScript 的 Date 对象是处理日期和时间的核心工具,它既能表示当前时间点,也能通过参数自定义时间。理解其构造函数和常用方法是入门的关键。

1.1 创建 Date 对象

Date 对象支持多种构造方式:

  • 获取当前时间
    const now = new Date();  
    console.log(now); // 输出类似:Sun Oct 01 2023 15:30:00 GMT+0800 (China Standard Time)  
    
  • 通过时间戳创建
    const timestamp = 1700000000; // 任意毫秒数  
    const specificTime = new Date(timestamp);  
    
  • 通过字符串解析时间
    const dateStr = "2023-10-01";  
    const parsedDate = new Date(dateStr);  
    

注意:字符串格式需符合 ISO 8601 标准(如 "YYYY-MM-DD"),否则可能因浏览器差异导致解析失败。

1.2 获取时间信息

通过 get 方法可提取日期的各个部分:
| 方法名称 | 说明 | 示例返回值 |
|------------------------|-------------------------------|----------------|
| getFullYear() | 获取四位年份 | 2023 |
| getMonth() | 获取月份(0 表示一月) | 9(10月) |
| getDate() | 获取日期(1-31) | 1 |
| getHours() | 获取小时(0-23) | 15 |
| getMinutes() | 获取分钟(0-59) | 30 |

案例:输出当前日期的完整描述:

function formatDate(date) {  
  const year = date.getFullYear();  
  const month = date.getMonth() + 1; // 转为1-12  
  const day = date.getDate();  
  return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;  
}  
console.log(formatDate(new Date())); // 2023-10-01  

二、日期格式化:让时间更“人友好”

JavaScript 原生的 Date 对象无法直接输出美观的格式,但可以通过手动拼接或借助工具库实现。

2.1 手动格式化日期

通过 get 方法组合字符串,可实现简单格式化:

function getReadableTime(date) {  
  const hours = date.getHours();  
  const minutes = date.getMinutes();  
  const period = hours >= 12 ? 'PM' : 'AM';  
  return `${hours % 12}:${minutes < 10 ? '0' + minutes : minutes} ${period}`;  
}  
const now = new Date();  
console.log(getReadableTime(now)); // 3:30 PM  

2.2 使用 Intl.DateTimeFormat(高级技巧)

Intl.DateTimeFormat 是 ES6 引入的国际化 API,能灵活控制日期显示格式:

const options = {  
  year: 'numeric',  
  month: 'long',  
  day: '2-digit',  
  hour: '2-digit',  
  minute: '2-digit',  
  timeZoneName: 'short',  
};  
const formatter = new Intl.DateTimeFormat('en-US', options);  
console.log(formatter.format(new Date())); // October 1, 2023, 3:30 PM GMT+8  

三、时间计算:加减日期与时差问题

日期的加减操作需借助毫秒时间戳,因为 Date 对象本质上是自 1970-01-01 以来的毫秒数。

3.1 基础计算逻辑

// 计算一周后的时间  
const oneWeekLater = new Date();  
oneWeekLater.setDate(oneWeekLater.getDate() + 7);  
// 或通过时间戳计算  
const timestamp = Date.now() + 7 * 24 * 60 * 60 * 1000;  

3.2 处理时区差异

Date 对象默认使用本地时区,但可通过 UTC 方法操作协调世界时(UTC):

// 获取 UTC 时间  
const utcYear = new Date().getUTCFullYear(); // UTC 年份  
const utcTime = new Date(Date.UTC(2023, 9, 1, 15, 30)); // 直接构造 UTC 时间  

四、常见陷阱与解决方案

4.1 月份从 0 开始的“坑”

getMonth() 返回 0-11,而非 1-12,需手动加 1:

// 错误写法  
const month = new Date().getMonth(); // 9 表示十月  
// 正确写法  
const fixedMonth = month + 1; // 10  

4.2 日期范围的边界问题

直接加减天数可能导致意外结果:

// 错误案例:假设当前是 2023-10-31  
const nextMonth = new Date();  
nextMonth.setDate(31 + 30); // 可能跳到 2023-12-01  

解决方案:使用 setMonth()getFullYear() 结合判断:

function addMonths(date, months) {  
  const newDate = new Date(date);  
  newDate.setMonth(newDate.getMonth() + months);  
  return newDate;  
}  

五、实战案例:构建倒计时功能

5.1 需求分析

实现一个显示“距离 2024-01-01 还剩多少天”的倒计时:

5.2 代码实现

function countdown(targetDate) {  
  const now = new Date();  
  const diff = targetDate - now;  
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));  
  const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));  
  return `距离目标还有 ${days} 天 ${hours} 小时`;  
}  
const target = new Date('2024-01-01');  
console.log(countdown(target)); // 根据当前时间动态输出  

六、扩展与工具推荐

6.1 第三方库:简化复杂场景

  • date-fns:轻量级函数式库,提供清晰 API:
    import { format } from 'date-fns';  
    console.log(format(new Date(), 'yyyy-MM-dd HH:mm:ss')); // 2023-10-01 15:30:00  
    
  • moment.js:功能强大但体积较大,适合复杂需求:
    const time = moment().format('MMMM Do YYYY, h:mm:ss a'); // October 1st 2023, 3:30:00 pm  
    

6.2 时区转换:使用 toLocaleString()

const date = new Date();  
console.log(date.toLocaleString('en-US', { timeZone: 'Asia/Shanghai' })); // 强制使用上海时区  

结论

掌握 js date 的核心方法和陷阱,能显著提升开发者处理时间相关功能的效率。从基础的日期创建、格式化,到进阶的时区处理和计算逻辑,每个环节都需要结合案例反复练习。对于复杂场景,合理借助第三方库可避免重复造轮子。希望本文能成为你探索 JavaScript 日期处理的实用指南!

最新发布