all files / src/ date.js

100% Statements 105/105
99.05% Branches 104/105
100% Functions 21/21
100% Lines 93/93
1 statement, 2 branches Ignored     
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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161       33× 33× 29×                               37×   37×   37× 57× 57× 57× 15×   42×   37× 35× 35×   33×   32×   28×   27×   26×                 40×     34×   30× 30×     11×     24×   22×   20×         37× 95× 95× 95× 95×     123× 123×   123× 88×   123× 86×   37× 37× 256×     95×         97× 97× 279× 279×   97× 97× 70× 70× 201×   70× 70× 70×   70× 70×   27×         70×   70×  
import messages from './messages'
import Validators from './index'
import { toObjectMsg, addMsgValues, prepare, trunc, memoize } from './helpers'
 
 
 
const DATE_METHODS = {
  y: function(d) { return d.getFullYear() },
  m: function(d) { return d.getMonth() + 1 },
  d: function(d) { return d.getDate() }
}
 
const PARSE_REG = /(y+|m+|d+)/g
 
const TO_STRING = ({}).toString;
 
let date = memoize(function ({
      format,
      ymd,
      '=': eq,
      '!=': diff,
      '>': gt,
      '>=': gte,
      '<': lt,
      '<=': lte,
      message, msg,
      'if': ifCond, unless,
      allowBlank
    }={}) {
 
  msg = toObjectMsg(msg || message)
 
  return prepare(ifCond, unless, allowBlank, function(value) {
    let normFormat = normalizeFormat(format, ymd)
    let date = normParseDate(value, normFormat, false)
    if ('wrongFormat' === date) {
      return Validators.formatMessage(msg || addMsgValues(messages.dateFormat, { format: format }))
    }
    if ('invalid' === date) {
      return Validators.formatMessage(msg || messages.dateInvalid)
    }
    if (date) {
      let date2
      if (eq && +date !== +(date2 = getDate(eq))) {
        return Validators.formatMessage(msg || addMsgValues(messages.dateRange, values('=', date2, normFormat)))
      }
      if (diff && +date === +(date2 = getDate(diff))) {
        return Validators.formatMessage(msg || addMsgValues(messages.dateRange, values('!=', date2, normFormat)))
      }
      if (gt && date <= (date2 = getDate(gt))) {
        return Validators.formatMessage(msg || addMsgValues(messages.dateRange, values('>', date2, normFormat)))
      }
      if (gte && date < (date2 = getDate(gte))) {
        return Validators.formatMessage(msg || addMsgValues(messages.dateRange, values('>=', date2, normFormat)))
      }
      if (lt && date >= (date2 = getDate(lt))) {
        return Validators.formatMessage(msg || addMsgValues(messages.dateRange, values('<', date2, normFormat)))
      }
      if (lte && date > (date2 = getDate(lte))) {
        return Validators.formatMessage(msg || addMsgValues(messages.dateRange, values('<=', date2, normFormat)))
      }
    }
  })
})
 
date.parseDate = parseDate
date.formatDate = formatDate
 
export default date
 
function parseDate (strDate, format, ymd) {
  return normParseDate(strDate, normalizeFormat(format, ymd), true)
}
 
function formatDate (date, format, ymd) {
  if (!(date instanceof Date) && '[object Date]' !== TO_STRING.call(date)) {
    return null;
  }
  let t = new Date(date).getTime();
  return t !== t ? null : normFormatDate(date, normalizeFormat(format, ymd))
}
 
function values (op, date, format) {
  return { op: op, date: normFormatDate(date, format), dateObject: date }
}
 
function getDate (d) {
  if ('function' === typeof d) {
    return new Date(+d())
  }
  if (isNaN(d) && 'today' === ('' + d).toLowerCase()) {
    let today = new Date()
    today.setHours(0, 0, 0, 0)
    return today
  }
  return new Date(+d)
}
 
 
// FORMAT
function normFormatDate (date, format) {
  return format.replace(PARSE_REG, function(m) {
    let sym = m.charAt(0)
    let len = m.length
    let padded = padding(DATE_METHODS[sym](date), len)
    return 'y' === sym ? padded.slice(padded.length - len, padded.length) : padded;
  })
}
function normalizeFormat (format, ymd) {
  if (null == format) {
    format = Validators.defaultOptions.dateFormat
  }
  if (!ymd) {
    ymd = Validators.defaultOptions.dateYmd
  }
  if (!ymd || 'ymd' === ymd) {
    return format
  }
  let reverseMapping = { [ymd.charAt(0)]: 'y', [ymd.charAt(1)]: 'm', [ymd.charAt(2)]: 'd' }
  return format.replace(new RegExp(`[${ymd}]`, 'g'), function(sym) {
    return reverseMapping[sym]
  })
}
function padding (num, pad) {
  return '0'.repeat(Math.max(0, pad - ('' + num).length)) + num
}
 
 
// PARSE
function normParseDate (value, format, parse) {
  let order = []
  let reg = new RegExp('^' + format.replace(PARSE_REG, function(m) {
    order.push(m.charAt(0))
    return `([0-9]{${m.length}})`
  }) + '$')
  let match = value.match(reg)
  if (match) {
    let flags = {}
    order.forEach(function(token, index) {
      flags[token] = +match[index + 1]
    })
    let comparable = null != flags.y ? (null != flags.m ? true : null == flags.d) : false
    flags = Object.assign({ y: 1970, m: 1, d: 1 }, flags)
    if (flags.y < 100) {
      flags.y = currentCentury(flags.y >= 69 ? -1 : 0) * 100 + flags.y
    }
    let date = new Date(flags.y, flags.m - 1, flags.d)
    return checkFlags(date, flags) ? (comparable || parse ? date : null) : (parse ? new Date(NaN) : 'invalid')
  }
  return parse ? new Date(NaN) : 'wrongFormat'
}
 
function currentCentury (add) {
  let century = trunc(new Date().getFullYear() / 100)
  return century < 0 ? century - add : century + add
}
 
function checkFlags (date, flags) {
  let [year, month, day] = [date.getFullYear(), date.getMonth() + 1, date.getDate()]
  return year === flags.y && month === flags.m && day === flags.d
}