日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 前端文檔 正文

JS 獲取指定日期所在月的第一天和最后一天

作者:donghua201 更新時(shí)間: 2024-03-05 前端文檔

?JS四舍五入保留兩位小數(shù)-CSDN博客

function getMonthStartAndEnd(dateString) {
  const date = dateString ? new Date(dateString) : new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  // const firstDay = new Date(year, month - 1, 1);
  const lastDay = new Date(year, month, 0);
  const formattedFirstDay = `${year}-${month.toString().padStart(2, '0')}-01`;
  const formattedLastDay = `${year}-${month.toString().padStart(2, '0')}-${lastDay.getDate()}`;
  return { firstDay: formattedFirstDay, lastDay: formattedLastDay };
}

console.log(getMonthStartAndEnd('2023-11-15'));
// { "firstDay": "2023-11-01", "lastDay": "2023-11-30" }

沒(méi)有傳入?yún)?shù),默認(rèn)為當(dāng)天日期。

首先根據(jù)傳入的日期字符串(或者當(dāng)前日期)創(chuàng)建一個(gè) Date 對(duì)象。然后通過(guò) Date 對(duì)象的方法獲取年份和月份,并計(jì)算出該月的最后一天的 Date 對(duì)象。第一天都是1號(hào),不用額外計(jì)算。

時(shí)間使用ES2017的padStart方法對(duì)兩位數(shù)補(bǔ)零。

獲取到的年月日數(shù)據(jù)后,使用模板字符串``拼接出?"YYYY-MM-DD" 的日期格式。

new Date(year, month, day)? 按給定的參數(shù)創(chuàng)建日期對(duì)象

在JavaScript中,創(chuàng)建Date對(duì)象時(shí),可以使用new Date(year, month, day)的形式返回指定日期,三個(gè)參數(shù)的含義如下:

  • year:年份,四位數(shù)的整數(shù)值。
  • month:月份,從0開(kāi)始計(jì)數(shù),范圍是0-11,其中0表示一月,1表示二月,依此類推。所以如果要獲取yyyy年mm月dd日,月份記得要-1,new Date(yyyy,mm-1,dd)。比如現(xiàn)在是12月,那么month要傳11。
  • day:日期,從1開(kāi)始計(jì)數(shù),范圍是1-31,具體取決于指定月份的天數(shù)。0表示上一個(gè)月的最后一天。
// 假設(shè)當(dāng)前是2023年11月(curr_year = 2023, curr_month = 10)。
let curr_year = 2023
let curr_month = 10

console.log(new Date(curr_year, curr_month, 0))
//curr_year為2023,curr_month為10(代表11月)。
//參數(shù)0表示上一個(gè)月的最后一天。
//Tue Oct 31 2023 00:00:00 GMT+0800 (中國(guó)標(biāo)準(zhǔn)時(shí)間)

console.log(new Date(curr_year, curr_month+1, 0))
//curr_year為2023,curr_month + 1表示下一個(gè)月,即12月。
//參數(shù)0表示上一個(gè)月的最后一天。
//Thu Nov 30 2023 00:00:00 GMT+0800 (中國(guó)標(biāo)準(zhǔn)時(shí)間)

console.log(new Date(curr_year, curr_month, 1))
//curr_year為2023,curr_month為10(代表11月)。
//參數(shù)1表示當(dāng)前月份的第一天。
//Wed Nov 01 2023 00:00:00 GMT+0800 (中國(guó)標(biāo)準(zhǔn)時(shí)間)

console.log(new Date(curr_year, curr_month+1, 1))
//curr_year為2023,curr_month + 1表示下一個(gè)月,即12月。
//參數(shù)1表示下一個(gè)月的第一天。
//Fri Dec 01 2023 00:00:00 GMT+0800 (中國(guó)標(biāo)準(zhǔn)時(shí)間)

原文鏈接:https://blog.csdn.net/donghua201/article/details/134715319

  • 上一篇:沒(méi)有了
  • 下一篇:沒(méi)有了
欄目分類
最近更新