Javascript|Date 对象&&基础使用方法

Date 对象用于处理日期与时间

创建 Date 对象: new Date()

// 创建 Date 对象:
let curDate = new Date('2024-01-01 08:30:59');
// 获取年份:四位数字返回年份
let year = curDate.getFullYear()
// 获取月份(返回月份 (0 ~ 11),记住+1)
let month = curDate.getMonth() + 1
// 获取日期(一个月中的某一天 (1 ~ 31))
let day = curDate.getDate()
// 获取小时(0 ~ 23)
let hours = curDate.getHours()
// 获取分钟(0 ~ 59)
let minutes = curDate.getMinutes()
// 获取秒数(0 ~ 59)
let seconds = curDate.getSeconds()
// 获取时间戳(返回 1970 年 1 月 1 日至今的毫秒数)
let curTime = curDate.getTime()
// 获取周值 (一周中的某一天 (0 ~ 6),周六——>6,周日——>0)
let weekDay = curDate.getDay()
// 获取某月的最后一天(第三个参数传入0)
let lastMonthDay = new Date('2024', '03', 0).getDate();
// 获取当前时间和时间戳转字符串
function getDateTime(date = 'now', format = "YYYY-MM-DD HH:mm:ss") {
    let newDate = date == 'now' ? new Date() : new Date(date);
    const config = {
        YYYY: newDate.getFullYear(),
        MM: newDate.getMonth() + 1 < 10 ? '0' + (newDate.getMonth() + 1) : newDate.getMonth() + 1,
        DD: newDate.getDate() < 10 ? '0' + newDate.getDate() : newDate.getDate(),
        HH: newDate.getHours() < 10 ? '0' + newDate.getHours() : newDate.getHours(),
        mm: newDate.getMinutes() < 10 ? '0' + newDate.getMinutes() : newDate.getMinutes(),
        ss: newDate.getSeconds() < 10 ? '0' + newDate.getSeconds() : newDate.getSeconds()
    };
    for (const key in config) {
        format = format.replace(key, config[key])
    }
    return format;
}
console.log('getDateTime', getDateTime(1704069059000, 'YYYY-MM-DD'));
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

94半猿人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值