JS 獲取當天所在月的最后一天日期,所在周的每天的日期,時間的計算


/**
 * 獲取當天所在月的最后一天日期,和下一個月的第一天日期
 * 調用getMonthDay(d), d默認值為01,d為要設置成的day;
 */
const getMonthMaxDay = () => {
  var curDate = new Date();
  var curMonth = curDate.getMonth();
  /*  生成實際的月份: 由於curMonth會比實際月份小1, 故需加1 */
  curDate.setMonth(curMonth + 1);
  /* 將日期設置為0, 返回當月最后一天日期, 將日期設置為1,返回下一個月第一天日期*/
  curDate.setDate(0);
  /* 返回當月的天數 */
  return curDate.getDate();
}

// 獲取當前月中第某一天的日期
export const getMonthDay = (d='01') => {
  const t = new Date();
  return `${t.getFullYear()}-${setT(t.getMonth() + 1)}-${d}`;
}
const setT = (e) => {
  return `${e}`.length > 1 ? `${e}` : `0${e}`;
}
getMonthDay() // return 2017-05-01
getMonthDay(getMonthMaxDay); //return 2017-05-31



/**
 * 獲取當天所在周的周一和周日的日期
 * 返回 YYYY-MM-DD 格式時間
 */
const setToday = function (t=(new Date())) {
  return `${t.getFullYear()}-${setT(t.getMonth() + 1)}-${setT(t.getDate())}`;
}
export const getWeekDay = () => {
  const date1 = new Date(),
        date2 = new Date();
  return {
    weekStart: setToday(new Date(date1.setDate(date1.getDate() - date1.getDay() + 1))), // Monday
    weekEnd: setToday( new Date(date2.setDate(date2.getDate() + (7 - date2.getDay())))), // Sunday
  };
}
getWeekDay() //return {weekStart: 2017-05-22, weekEnd: 2017-05-28}

/**
 * 對時間進行加減運算
 * calcTime(t, d) t參數為要進行計算的日期,d為時間差
 * 返回 YYYY-MM-DD HH:mm:ss 格式時間
 */
const setFullTime = function(t=(new Date())) {
  return `${t.getFullYear()}-${setT(t.getMonth() + 1)}-${setT(t.getDate())} ${setT(t.getHours())}:${setT(t.getMinutes())}:${setT(t.getSeconds())}`;
}
export const calcTime = (t, d) => {
  var date1 = new Date((t).replace(/-/g, '/')),
      date2 = (date1/1000 + d)*1000,
      date3 = new Date(date2);
  return setFullTime(date3);
};
const d1 = '2017-05-26 18:08:45';
cosnt d = -30;
calcTime(d1, d) // return 2017-05-26 18:08:15

---------------------

本文來自 OutbreakUniverse 的CSDN 博客 ,全文地址請點擊:https://blog.csdn.net/HobbitHero/article/details/72765042?utm_source=copy 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM