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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章