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

JS date 官方地址

/**
 * 獲取當天所在月的最後一天日期,和下一個月的第一天日期
 * 調用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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章