当前位置: 首页 > news >正文

JavaScript日期对象

目录

一、实例化日期对象

1. 无参数:获取当前时间

2. 传入时间戳

3. 传入日期字符串

4. 传入年月日时分秒

5. 其他格式

二、日期对象常用方法

1. 获取日期时间分量

2. 设置日期时间分量

3. UTC 方法

4. 日期格式化

三、时间戳(Timestamp)

1. 获取时间戳

2. 时间戳转换日期

3. 计算时间差

四、常见场景与注意事项

1. 月份索引从 0 开始

2. 日期比较

3. 时区处理

示例:实时倒计时


JavaScript 中的 Date 对象用于处理日期和时间,支持创建、操作和格式化日期。


一、实例化日期对象

1. 无参数:获取当前时间

const now = new Date();
console.log(now); // 输出当前本地时间,如:Fri Jul 12 2024 14:30:45 GMT+0800 (中国标准时间)

2. 传入时间戳

时间戳是从 1970-1-1 00:00:00 UTC 至今的毫秒数。

const timestamp = 1720785600000; // 代表 2024-07-12 12:00:00 UTC
const dateFromTimestamp = new Date(timestamp);
console.log(dateFromTimestamp); // 转换为本地时间

3. 传入日期字符串

支持符合规范的日期字符串(如 ISO 8601 格式)。

const dateFromString = new Date("2024-07-12T12:00:00Z"); // UTC 时间
console.log(dateFromString); // 转换为本地时间

4. 传入年月日时分秒

注意:月份从 0 开始(0 代表 1 月,11 代表 12 月)。

// 语法:new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds)
const specificDate = new Date(2024, 6, 12, 14, 30, 0); // 2024年7月12日 14:30:00
console.log(specificDate);

5. 其他格式

// 仅传入年月日
const datePart = new Date(2024, 6, 12); // 2024-07-12 00:00:00

// 使用逗号分隔参数
const dateWithParams = new Date(2024, 6, 12, 14, 30); // 2024-07-12 14:30:00

二、日期对象常用方法

1. 获取日期时间分量

方法说明示例
getFullYear()获取四位年份(推荐)2024
getMonth()获取月份(0-11)6(代表7月)
getDate()获取月份中的第几天(1-31)12
getHours()获取小时(0-23)14
getMinutes()获取分钟(0-59)30
getSeconds()获取秒(0-59)0
getMilliseconds()获取毫秒(0-999)500
getDay()获取星期几(0-6,0=周日)5(代表周六)

示例

const date = new Date(2024, 6, 12, 14, 30, 45, 500);
console.log(date.getFullYear());  // 2024
console.log(date.getMonth());     // 6(7月)
console.log(date.getDate());      // 12
console.log(date.getDay());       // 5(周六)

2. 设置日期时间分量

方法说明
setFullYear(year)设置年份
setMonth(month)设置月份(0-11)
setDate(day)设置月份中的第几天
setHours(hours)设置小时(可连锁设置其他分量)

示例

const date = new Date();
date.setFullYear(2025);
date.setMonth(11); // 设置为12月
date.setDate(31);  // 设置为31号
console.log(date); // 2025-12-31 ...

3. UTC 方法

处理 UTC 时间(世界标准时间):

const date = new Date();
console.log(date.getUTCFullYear());  // UTC 年份
console.log(date.getUTCHours());     // UTC 小时

4. 日期格式化

方法说明示例输出
toString()完整日期时间字符串Fri Jul 12 2024 14:30:45 GMT+0800
toDateString()仅日期部分Fri Jul 12 2024
toTimeString()仅时间部分14:30:45 GMT+0800
toISOString()ISO 8601 格式的 UTC 时间2024-07-12T06:30:45.000Z
toLocaleDateString()本地格式的日期2024/7/12
toLocaleTimeString()本地格式的时间14:30:45

示例

const date = new Date();
console.log(date.toISOString());      // 2024-07-12T06:30:45.000Z
console.log(date.toLocaleDateString()); // 2024/7/12(根据系统区域设置)

三、时间戳(Timestamp)

1. 获取时间戳

方法说明
Date.now()当前时间戳(毫秒)
date.getTime()日期对象对应的时间戳
date.valueOf()等价于 getTime()

示例

const timestamp1 = Date.now();        // 当前时间戳
const date = new Date();
const timestamp2 = date.getTime();    // 等同于 date.valueOf()
console.log(+new Date());

2. 时间戳转换日期

const timestamp = 1720785600000;
const date = new Date(timestamp);
console.log(date.toISOString()); // 2024-07-12T12:00:00.000Z

3. 计算时间差

const start = Date.now();
// 执行一些操作...
const end = Date.now();
const duration = end - start; // 毫秒级耗时
console.log(`耗时:${duration}ms`);

四、常见场景与注意事项

1. 月份索引从 0 开始

// 错误写法:将 7 月写成 7
const wrongDate = new Date(2024, 7, 12); // 实际是 8月12日

// 正确写法:7 月对应 6
const correctDate = new Date(2024, 6, 12); // 7月12日

2. 日期比较

直接比较日期对象或时间戳:

const date1 = new Date(2024, 6, 12);
const date2 = new Date(2024, 6, 15);
console.log(date1 < date2); // true

// 或比较时间戳
console.log(date1.getTime() < date2.getTime()); // true

3. 时区处理

  • 转换为 UTC 时间

    const date = new Date();
    console.log(date.toISOString()); // UTC 时间
  • 解析 UTC 时间字符串

    const utcDate = new Date("2024-07-12T12:00:00Z"); // 明确指定 UTC

示例:实时倒计时

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>实时倒计时</title>
  <style>
    #countdown {
      font-size: 24px;
      font-family: Arial, sans-serif;
      padding: 20px;
      background: #f0f0f0;
      border-radius: 8px;
      display: inline-block;
    }

    .time-unit {
      margin: 0 10px;
      padding: 5px 10px;
      background: white;
      border-radius: 4px;
    }
  </style>
</head>

<body>
  <h2>距离2026年元旦还有:</h2>
  <div id="countdown">
    <span class="time-unit" id="days">00</span>天
    <span class="time-unit" id="hours">00</span>小时
    <span class="time-unit" id="minutes">00</span>分
    <span class="time-unit" id="seconds">00</span>秒
  </div>

  <script>
    // 目标时间:2026年1月1日 00:00:00 (本地时间)
    const targetDate = new Date(2026, 0, 1, 0, 0, 0);

    // 获取显示元素
    const daysElement = document.getElementById('days');
    const hoursElement = document.getElementById('hours');
    const minutesElement = document.getElementById('minutes');
    const secondsElement = document.getElementById('seconds');

    // 时间格式化函数(补零)
    function formatTime(number) {
      return number.toString().padStart(2, '0');
    }

    // 倒计时计算函数
    function updateCountdown() {
      const currentDate = new Date();
      const timeDifference = targetDate - currentDate;

      if (timeDifference <= 0) {
        clearInterval(timer);
        document.getElementById('countdown').innerHTML = "新年快乐!";
        return;
      }

      // 计算时间分量
      const seconds = Math.floor(timeDifference / 1000) % 60;
      const minutes = Math.floor(timeDifference / (1000 * 60)) % 60;
      const hours = Math.floor(timeDifference / (1000 * 60 * 60)) % 24;
      const days = Math.floor(timeDifference / (1000 * 60 * 60 * 24));

      // 更新显示
      daysElement.textContent = formatTime(days);
      hoursElement.textContent = formatTime(hours);
      minutesElement.textContent = formatTime(minutes);
      secondsElement.textContent = formatTime(seconds);
    }

    // 立即执行一次避免初始空白
    updateCountdown();

    // 启动定时器(每秒更新)
    var timer = setInterval(updateCountdown, 1000);
  </script>
</body>

</html>

http://www.dtcms.com/a/108813.html

相关文章:

  • Python 编程实战:打造高效便捷的目录结构生成器
  • 踩坑ubuntu24.04 编译vtk9.3.1的安卓版本
  • 前端开发技术演进与就业现实:顺应时代方能不被淘汰-优雅草卓伊凡
  • ubantu执行sudo chown -R username xxx(文件夹)命令失效
  • 推荐系统(二十一):基于MaskNet的商品推荐CTR模型实现
  • OpenCV 图形API(12)用于计算图像或矩阵的平均值函数mean()
  • dify开启多租户模式
  • Coco-AI 支持嵌入,让你的网站拥有 AI 搜索力
  • 基于javaweb的SSM+Maven机房管理系统设计与实现(源码+文档+部署讲解)
  • 智慧高炉厂可视化:钢铁行业的数字化转型之路
  • leetcode31.下一个排列
  • 42.C++11-右值引用与移动语义/完美转发
  • Real-Time Anomaly Detection of Network Traffic Basedon CNN
  • 动、静态创建任务
  • 实战打靶集锦-37-Wpwnvm
  • GUI-Guider 按钮按下 选项卡 右移动一个,到最右边停下
  • BMS电池关键参数及其含义
  • Lua中debug调试函数详解
  • 【DLI】Generative AI with Diffusion Models通关秘籍
  • Redis基础知识-2
  • 从零构建大语言模型全栈开发指南:第五部分:行业应用与前沿探索-5.1.1百度ERNIE、阿里通义千问的技术对比
  • 程序化广告行业(56/89):S2S对接与第三方广告监测全解析
  • 《第三次世界大战》第七章:破碎的未来
  • 《实战AI智能体》MCP对Agent有哪些好处
  • [CISSP] [7] PKI和密码应用
  • 应用安全系列之四十五:日志伪造(Log_Forging)之二
  • 基于BusyBox构建ISO镜像
  • 多模态模型:专栏概要与内容目录
  • 网络爬虫的基础知识
  • 《inZOI(云族裔)》50+MOD整合包