js获取当前时间,指定月份的第一天和最后一天

本文介绍了如何使用JavaScript获取当前选定月份的第一天和最后一天。通过设置日期为1获取月初,通过获取下个月第一天并减去一天得到月末。
摘要由CSDN通过智能技术生成

//获取当前月份
page.getNowFormatDate = function() {
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate ;
    return currentdate;
};


<

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
获取当前月份第一天最后一天的时间戳,可以使用 JavaScript 的 Date 对象,结合 `getTime()` 方法。具体的代码如下所示: ```javascript const now = new Date(); // 获取当前时间 const year = now.getFullYear(); // 年份 const month = now.getMonth() + 1; // 月份,注意要加 1 const firstDay = new Date(year, month - 1, 1); // 当前月份第一天 const lastDay = new Date(year, month, 0); // 当前月份最后一天 const firstDayTimestamp = firstDay.getTime(); // 当前月份第一天的时间戳 const lastDayTimestamp = lastDay.getTime(); // 当前月份最后一天的时间戳 console.log(`当前月份第一天的时间戳:${firstDayTimestamp}`); // 输出:当前月份第一天的时间戳:1633046400000 console.log(`当前月份最后一天的时间戳:${lastDayTimestamp}`); // 输出:当前月份最后一天的时间戳:1635638399999 ``` 在上面的代码中,我们首先使用 `new Date()` 获取当前时间,然后通过 `getFullYear()` 和 `getMonth()` 方法获取当前的年份和月份。接着,我们使用 `new Date(year, month - 1, 1)` 创建了一个新的 Date 对象,其中 `year` 和 `month - 1` 分别表示年份和月份,`1` 表示天数,即当前月份第一天。同样地,我们使用 `new Date(year, month, 0)` 创建了另一个 Date 对象,其中 `year` 和 `month` 分别表示年份和月份,`0` 表示天数,即当前月份最后一天最后,我们使用 `getTime()` 方法获取了当前月份第一天最后一天的时间戳,并输出到控制台。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值