争渡,争渡,惊起一滩鸥鹭

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

 

万能时间处理器:

/**
 *时间格式化处理
 *
 * @export
 * @param {*} d 需要处理的时间
 * @param {*} fmt 格式化样式 如:"yyyy-MM-dd hh:mm:ss"  默认: "yyyy-MM-dd" 
 * @returns
 */
export function formatDate(d, fmt = "yyyy-MM-dd") {
  var date = d ? new Date(d) : new Date();
  var o = {
    "M+": date.getMonth() + 1,                 //月份   
    "d+": date.getDate(),                    //
    "h+": date.getHours(),                   //小时   
    "m+": date.getMinutes(),                 //
    "s+": date.getSeconds(),                 //
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度   
    "S": date.getMilliseconds()             //毫秒   
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

 

  // 当前月份(第一天至最后一天)
    nowMonthInterval() {
      let myDate = new Date();
      let currentMonth = myDate.getMonth();
      let firstDay = new Date(myDate.getFullYear(), currentMonth, 1);
      let lastDay = new Date(firstDay.getFullYear(), currentMonth + 1, 0);
      this.nowMonth = [formatDate(firstDay), formatDate(lastDay)]; // 当前月份(第一天至最后一天)
    },
    // 当前年份(第一天至最后一天)
    nowYearInterval() {
      let firstDay = new Date();
      firstDay.setDate(1);
      firstDay.setMonth(0);
      let lastDay = new Date();
      lastDay.setFullYear(lastDay.getFullYear() + 1);
      lastDay.setDate(0);
      lastDay.setMonth(-1);
      this.nowYear = [formatDate(firstDay), formatDate(lastDay)]; // 当前年份(第一天至最后一天)
    },

 

当用上面方法获取当前年份(第一天至最后一天)时,如果用new Date()获取的月份是2月时,当前年份的最后一天居然是28日(正确是31日),所以才有如下的方法:

    // 当前年份(第一天至最后一天)
    nowYearInterval() {
      // 第一天
      let firstDay = new Date();
      firstDay.setDate(1);
      firstDay.setMonth(0);
      // 最后一天(直接算当年12月的最后一天)
      let nowYear = formatDate(new Date(), "yyyy");
      let exampleNowYear = nowYear + "-12-12";
      let myDate = new Date(exampleNowYear);
      let currentMonth = myDate.getMonth();
      let firstDay111 = new Date(myDate.getFullYear(), currentMonth, 1);
      let lastDay = new Date(firstDay111.getFullYear(), currentMonth + 1, 0);

      this.nowYear = [formatDate(firstDay), formatDate(lastDay)]; // 当前年份(第一天至最后一天)
    },

 

 

判断两个日期是否相等:

      let date1 = new Date(formatDate("2020-02-23 18:30")).getTime();
      let date2 = new Date(formatDate("2020-02-23 19:30")).getTime();
      if (date1 == date2) {
        console.log("日期相等")
      }

 

参考文档:https://blog.csdn.net/zl_action/article/details/101026969

 

posted on 2020-02-23 18:13  争渡~  阅读(407)  评论(0)    收藏  举报