All files / date getTimeSplit.js

100% Statements 28/28
78.57% Branches 11/14
100% Functions 1/1
100% Lines 28/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81                                                1x   1x   1x                 6x 1x     5x 5x     5x 5x   5x 5x 1x   5x 5x 5x 5x 5x   5x 5x   5x 5x   5x 2x   5x 1x     5x         5x     1x  
/**
 * 获取某个时间的 整年|整月|整日|整时|整分 时间对象
 * @method date/getTimeSplit
 * @param {Number|Date} time 实际时间
 * @param {String} type 单位时间类型,可选 ['year', 'month', 'week', 'day', 'hour']
 * @returns {Date} 时间整点对象
 * @example
 * var $getTimeSplit = require('@spore-ui/kit/packages/date/getTimeSplit');
 * new Date(
 *   $getTimeSplit(
 *     '2018-09-20',
 *     'month'
 *   )
 * ).toGMTString();
 * // Sat Sep 01 2018 00:00:00 GMT+0800 (中国标准时间)
 *
 * new Date(
 *   $getTimeSplit(
 *     '2018-09-20 19:23:36',
 *     'hour'
 *   )
 * ).toGMTString();
 * // Thu Sep 20 2018 19:00:00 GMT+0800 (中国标准时间)
 */
var $getUTCDate = require('./getUTCDate');
 
var DAY = 24 * 60 * 60 * 1000;
 
var TIME_UNITS = [
  'hour',
  'day',
  'week',
  'month',
  'year',
];
 
function getTimeSplit(time, type) {
  if (!type) {
    throw new Error('required param type');
  }
 
  var localTime = new Date(time);
  var utcTime = $getUTCDate(time);
 
  // 以周一为起始时间
  var day = utcTime.getDay();
  day = day === 0 ? 6 : day - 1;
 
  var index = TIME_UNITS.indexOf(type);
  if (index === 2) {
    utcTime = new Date(localTime - day * DAY);
  }
  var year = utcTime.getUTCFullYear();
  var month = utcTime.getUTCMonth() + 1;
  var date = utcTime.getUTCDate();
  var hour = utcTime.getUTCHours();
  var minutes = utcTime.getUTCMinutes();
 
  Eif (index >= 0) {
    minutes = '00';
  }
  Eif (index >= 1) {
    hour = '00';
  }
  if (index >= 3) {
    date = 1;
  }
  if (index >= 4) {
    month = 1;
  }
 
  var str = [
    [year, month, date].join('/'),
    [hour, minutes].join(':'),
  ].join(' ');
 
  return new Date(str);
}
 
module.exports = getTimeSplit;