1. 程式人生 > 實用技巧 >javascript時間函式封裝

javascript時間函式封裝

javascript時間函式封裝

 * 判斷時候是1-9,是的話就在前面新增0,變成01-09
 * @param n 字串
 */
export const formatNumber = function(n) {
  n = n.toString();
  return n[1] ? n : '0' + n;
};

/**
 * 時間戳和日期時間轉換(年月日+時間)
 * 時間格式:YYYY-MM-DD hh:mm:ss
 * @param times
 */
export const formatDateTime = function(times) {
  var now = new Date(times);
  var year = now.getFullYear();
  //注意月份需要加1,返回值0-11
  var month = now.getMonth() + 1;
  var date = now.getDate();
  var hour = now.getHours();
  var minute = now.getMinutes();
  var second = now.getSeconds();
  return year + '-' + formatNumber(month) + '-' + formatNumber(date) + ' ' + formatNumber(hour) + ':' + formatNumber(minute) + ':' + formatNumber(second);
};

/**
 * 時間戳和日期轉換(年月日)
 * 格式:YYYY-MM-DD
 * @param {*} times
 */
export const formatDate = function(times) {
  var now = new Date(times);
  var year = now.getFullYear();
  var month = now.getMonth() + 1;
  var date = now.getDate();
  return year + '-' + formatNumber(month) + '-' + formatNumber(date);
};

/**
 * 時間戳轉為 年月格式
 * 格式:YYYY-MM
 * @param {*} times
 */
export const formatYear = function(times) {
  var now = new Date(times);
  var year = now.getFullYear();
  var month = now.getMonth() + 1;
  return year + '-' + formatNumber(month);
};

/**
 * 時間戳轉為 月日格式
 * 格式:MM-DD
 * @param {*} times
 */
export const formatMonth = function(times) {
  var now = new Date(times);
  var month = now.getMonth() + 1;
  var date = now.getDate();
  return formatNumber(month) + '-' + formatNumber(date);
};

/**
 * 獲取一個月的第一天
 * @param {標準時間} times
 */
export const getCurrentMonthFirst = function(times) {
  var now = new Date(times);
  now.setDate(1);
  var month = parseInt(now.getMonth() + 1);
  var date = now.getDate();
  return now.getFullYear() + '-' + formatNumber(month) + '-' + formatNumber(date);
};

/**
 * 獲取一個月的最後一天
 * @param {標準時間} times
 */
export const getCurrentMonthLast = function(times) {
  var now = new Date(times);
  var year = now.getFullYear();
  var month = now.getMonth() + 1;
  var endOfMonth = new Date(year, month, 0).getDate();
  return now.getFullYear() + '-' + formatNumber(month) + '-' + endOfMonth;
};

/**
 *  獲取當月的天數
 */
export const mGetDate = function() {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  //獲取本月的第0天就是上月的最後一天
  const days = new Date(year, month, 0);
  return days.getDate();
};
/**
 * 獲取本週所有日期
 */
export const getWeekDay = function() {
  const date = new Date();
  const Monday = formatMonth(date.setDate(date.getDate() - date.getDay() + 1));
  const Tuesday = formatMonth(date.setDate(date.getDate() - date.getDay() + 2));
  const Wednesday = formatMonth(date.setDate(date.getDate() - date.getDay() + 3));
  const Thursday = formatMonth(date.setDate(date.getDate() - date.getDay() + 4));
  const Friday = formatMonth(date.setDate(date.getDate() - date.getDay() + 5));
  const Saturday = formatMonth(date.setDate(date.getDate() - date.getDay() + 6));
  const Sunday = formatMonth(date.setDate(date.getDate() - date.getDay() + 7));
  const weekDay = [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday];
  return weekDay;
};
/**
 * 獲取當月所有日期
 */
export const getNowM = function() {
  let now = new Date();
  let current_month_num = mGetDate();
  let current_month = [];
  for (let i = 1; i <= current_month_num; i++) {
    let day = now.setDate(i);
    let everyDay = formatMonth(day);
    current_month.push(everyDay);
  }
  return current_month;
};

/**
 * 計算時間差
 * @param {Data} startTime 開始時間
 * @param {Data} endTime   結束時間
 * return xx年xx天  || xx天xx小時 || xx小時xx分
 */
export const getDateDiff = function(startTime, endTime) {
  var sTime = new Date(startTime); //開始時間
  var eTime = new Date(endTime); //結束時間
  var timeOff = eTime - sTime; //相差時間戳(毫秒數)
  var timeMinute = 1000 * 60;
  var timeHour = 1000 * 3600;
  var timeDay = 1000 * 3600 * 24;
  var timeYear = 1000 * 3600 * 24 * 365;
  if (timeOff / timeYear >= 1) {
    return parseInt(timeOff / timeYear) + '年' + parseInt((timeOff % timeYear) / timeDay) + '天';
  } else if (timeOff / timeDay >= 1) {
    return parseInt(timeOff / timeDay) + '天' + parseInt((timeOff % timeDay) / timeHour) + '小時';
  } else {
    return parseInt(timeOff / timeHour) + '小時' + parseInt((timeOff % timeHour) / timeMinute) + '分';
  }
};

/**
 * 按照使用者需要格式化時間
 * @param {Data} times 標準時間
 * @param {String} rule 格式化規則
 */
export const FormatDate = function(date, format) {
  if (!date || date === '') {
    return '';
  }
  if (!format || format === '') {
    return formatDateTime(date);
  }

  if (typeof date === 'string') {
    var mts = date.match(/(\/Date\((\d+)\)\/)/);
    if (mts && mts.length >= 3) {
      date = parseInt(mts[2]);
    }
  }

  date = new Date(date);
  if (!date || date.toUTCString() === 'Invalid Date') {
    return '';
  }

  var map = {
    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(), // 毫秒
  };

  format = format.replace(/([yMdhmsqS])+/g, function(all, t) {
    var v = map[t];
    if (v !== undefined) {
      if (all.length > 1) {
        v = '0' + v;
        v = v.substr(v.length - 2);
      }
      return v;
    } else if (t === 'y') {
      return (date.getFullYear() + '').substr(4 - all.length);
    }
    return all;
  });
  return format;
};