JavaScript-----获取本周第一天、最后一天的日期

 

      /**

 

 
* 本周点击事件
*/
$scope.currentWeek = function(){
    var date = new Date();
    // 本周一的日期
    date.setDate(date.getDate() - date.getDay() + 1);
    var begin = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 00:00:00";
  
    // 本周日的日期
    date.setDate(date.getDate() + 6);
    var end = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 23:59:59";
        
    $scope.registDate(begin,end);
}
 
 
 
 
 
 
 
 
 
 
 
 
 
你可以使用 JavaScript 中的 Date 对象和一些日期操作方法来获取上月第一天至上月最后一天日期,并将其格式化为 `yyyy-mm-dd` 的字符串格式。 以下是获取上月第一天最后一天日期并格式化为 `yyyy-mm-dd` 字符串的代码示例: ```javascript // 获取当前日期 const today = new Date(); // 获取上月的年份和月份 const lastMonthYear = today.getFullYear(); const lastMonth = today.getMonth() - 1; if (lastMonth < 0) { lastMonthYear--; lastMonth = 11; } // 获取上月的第一天最后一天日期 const firstDayOfLastMonth = new Date(lastMonthYear, lastMonth, 1); const lastDayOfLastMonth = new Date(lastMonthYear, lastMonth + 1, 0); // 格式化日期字符串 const formatDate = (date) => { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); return `${year}-${month}-${day}`; }; const firstDayOfLastMonthStr = formatDate(firstDayOfLastMonth); const lastDayOfLastMonthStr = formatDate(lastDayOfLastMonth); console.log('上月第一天日期为:', firstDayOfLastMonthStr); console.log('上月最后一天日期为:', lastDayOfLastMonthStr); ``` 以上代码中,我们首先获取当前日期,然后计算上月的年份和月份。接着使用 `new Date()` 构造函数和年、月、日参数来创建上月第一天最后一天日期对象。最后定义了一个 `formatDate()` 函数,用于将日期对象格式化为 `yyyy-mm-dd` 的字符串。最后调用该函数将上月第一天最后一天日期对象格式化为字符串并输出到控制台。 需要注意的是,JavaScript 中的日期操作存在时区问题,可能会导致日期计算错误。因此建议在进行日期计算时,将所有日期都转换为 UTC 时间进行计算,再转换回本地时间。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值