JavaScript 日期对象

在 JavaScript 中,你可以使用 Date 对象来处理日期和时间。以下是一些常见的 Date 对象的使用方法:

1、创建日期对象:

html 复制代码
// 创建一个表示当前日期和时间的 Date 对象
let currentDate = new Date();

// 创建一个特定日期和时间的 Date 对象
let specificDate = new Date("2024-04-25T12:00:00");

// 也可以传入年、月、日等参数来创建 Date 对象
let customDate = new Date(2024, 3, 25); // 月份是从 0 开始计数,所以 3 表示四月

2、获取日期和时间的各个部分:

html 复制代码
let year = currentDate.getFullYear();
let month = currentDate.getMonth(); // 0 表示一月,11 表示十二月
let day = currentDate.getDate();
let hours = currentDate.getHours();
let minutes = currentDate.getMinutes();
let seconds = currentDate.getSeconds();
let milliseconds = currentDate.getMilliseconds();

3、设置日期和时间的各个部分:

html 复制代码
currentDate.setFullYear(2025);
currentDate.setMonth(4); // 设置为五月
currentDate.setDate(1);
currentDate.setHours(12);
currentDate.setMinutes(0);
currentDate.setSeconds(0);
currentDate.setMilliseconds(0);

4、格式化日期和时间为字符串:

html 复制代码
let formattedDate = currentDate.toISOString(); // 返回 ISO 8601 格式的字符串
console.log(formattedDate); // 输出类似 "2024-04-25T12:00:00.000Z" 的字符串

5、计算日期之间的差值:

html 复制代码
let diffInMilliseconds = specificDate.getTime() - currentDate.getTime();
let diffInSeconds = diffInMilliseconds / 1000;
let diffInMinutes = diffInMilliseconds / (1000 * 60);
// 同样,你也可以计算小时、天数等

有时候需要对时间进行补零操作。比如:09:01:08等

6、简单的页面倒计时代码(js部分):

html 复制代码
// 设置目标日期和时间(倒计时结束时间)
const targetDate = new Date("2024-12-31T23:59:59").getTime();

// 更新倒计时函数
function updateCountdown() {
    // 获取当前时间
    const currentDate = new Date().getTime();

    // 计算距离目标日期的时间差(毫秒数)
    const distance = targetDate - currentDate;

    // 计算倒计时的天、时、分、秒
    const days = Math.floor(distance / (1000 * 60 * 60 * 24));
    const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // 更新页面上的倒计时显示
    const countdownElement = document.getElementById('countdown');/获取盒子的id
    countdownElement.innerHTML = `倒计时:${days}天 ${hours}时 ${minutes}分 ${seconds}秒`;

    // 如果目标日期已过,则显示倒计时结束
    if (distance < 0) {
        countdownElement.innerHTML = "倒计时结束";
    }
}

// 初始调用一次更新倒计时函数,确保页面加载时立即显示正确的倒计时
updateCountdown();

// 每秒调用一次更新倒计时函数,实现实时更新倒计时
setInterval(updateCountdown, 1000);
相关推荐
Jiaberrr5 分钟前
Element UI教程:如何将Radio单选框的圆框改为方框
前端·javascript·vue.js·ui·elementui
XKSYA(小巢校长)34 分钟前
NatGo我的世界联机篇
开发语言·php
Cons.W37 分钟前
Codeforces Round 975 (Div. 1) C. Tree Pruning
c语言·开发语言·剪枝
憧憬成为原神糕手39 分钟前
c++_ 多态
开发语言·c++
VBA633740 分钟前
VBA信息获取与处理第三个专题第三节:工作薄在空闲后自动关闭
开发语言
wjs20242 小时前
XSLT 实例:掌握 XML 转换的艺术
开发语言
萧鼎2 小时前
Python第三方库选择与使用陷阱避免
开发语言·python
安冬的码畜日常2 小时前
【D3.js in Action 3 精译_029】3.5 给 D3 条形图加注图表标签(上)
开发语言·前端·javascript·信息可视化·数据可视化·d3.js
一颗星星辰2 小时前
C语言 | 第十章 | 函数 作用域
c语言·开发语言
lxp1997412 小时前
php函数积累
开发语言·php