返回

Date的基本使用以及常见用法

前端

Date的基本使用

  1. 创建Date对象

    // 创建当前日期和时间
    const now = new Date();
    
    // 创建指定日期和时间
    const specificDate = new Date(2023, 6, 15, 18, 30, 0);
    
  2. 获取日期和时间信息

    // 获取年、月、日、时、分、秒
    const year = now.getFullYear();
    const month = now.getMonth() + 1;  // 月份从 0 开始计数,所以要加 1
    const date = now.getDate();
    const hours = now.getHours();
    const minutes = now.getMinutes();
    const seconds = now.getSeconds();
    
    // 获取毫秒
    const milliseconds = now.getMilliseconds();
    
    // 获取星期几
    const day = now.getDay();  // 星期几,0 代表星期天,6 代表星期六
    
  3. 设置日期和时间信息

    // 设置年、月、日、时、分、秒
    now.setFullYear(2024);
    now.setMonth(11);  // 月份从 0 开始计数,所以这里设置 11 代表 12 月
    now.setDate(31);
    now.setHours(12);
    now.setMinutes(0);
    now.setSeconds(0);
    
    // 设置毫秒
    now.setMilliseconds(0);
    

Date的常见用法

  1. 获取当前时间戳

    // 获取当前时间戳(单位:毫秒)
    const timestamp = Date.now();
    
  2. 格式化日期和时间

    // 使用 toLocaleDateString() 格式化日期
    const formattedDate = now.toLocaleDateString();
    
    // 使用 toLocaleTimeString() 格式化时间
    const formattedTime = now.toLocaleTimeString();
    
    // 使用 toLocaleString() 格式化日期和时间
    const formattedDateTime = now.toLocaleString();
    
  3. 比较日期和时间

    // 比较两个日期对象的大小
    const date1 = new Date('2023-07-15');
    const date2 = new Date('2023-08-15');
    
    const comparisonResult = date1.getTime() - date2.getTime();
    
    if (comparisonResult > 0) {
      console.log('date1 is later than date2');
    } else if (comparisonResult < 0) {
      console.log('date1 is earlier than date2');
    } else {
      console.log('date1 is the same as date2');
    }
    
  4. 添加或减去日期和时间

    // 添加 10 天
    now.setDate(now.getDate() + 10);
    
    // 减去 30 分钟
    now.setMinutes(now.getMinutes() - 30);
    
  5. 创建定时器

    // 创建一个在 5 秒后执行的定时器
    const timeoutId = setTimeout(() => {
      console.log('5 seconds have passed!');
    }, 5000);
    
    // 取消定时器
    clearTimeout(timeoutId);
    
  6. 创建计时器

    // 创建一个每 1 秒执行一次的计时器
    const intervalId = setInterval(() => {
      console.log('1 second has passed!');
    }, 1000);
    
    // 取消计时器
    clearInterval(intervalId);
    

总结

Date对象是 JavaScript 中处理日期和时间的重要工具,它提供了丰富的API,可以轻松实现各种日期和时间操作。掌握Date对象的使用方法,可以大大提高你的编程效率。