返回列表

一个不错的时间处理工具库 date-fns startOfDay, endOfDay, endOfToday, endOfYesterday, subDays toDateRange

默认分类 2019/05/15 07:30

先安装 npm 包:

npm install date-fns@1.29.0

代码如下:

import {format, startOfDay, endOfDay, endOfToday, endOfYesterday, subDays} from 'date-fns'

export function toYesterdayDateRange (step = 30) {
  const to = format(endOfYesterday(), 'YYYY-MM-DD')
  const from = format(subDays(to, step).getTime() - 1000, 'YYYY-MM-DD')

  return [from, to]
}

export function toTodayDateRange (step = 30) {
  const to = format(endOfToday(), 'YYYY-MM-DD')
  const from = format(subDays(to, step).getTime() - 1000, 'YYYY-MM-DD')

  return [from, to]
}

export function toDateRange (from, to) {
  return [format(startOfDay(from), 'YYYY-MM-DD'), format(endOfDay(to), 'YYYY-MM-DD')]
}

export function fromDateRange ([from, to]) {
  const fromTime = startOfDay(from).getTime()
  const toTime = endOfDay(to).getTime()

  return {fromTime, toTime}
}

export function formaterMoney (val, fixed = 0) {
  const str = +val === val ? val.toFixed(fixed) + '' : val + ''
  const res = str.split('').reverse().join('').replace(/(\d{3}(?=\d)(?!\d+\.|$))/g, '$1,').split('').reverse().join('')

  return res
}

export function formatCurrency (value, decimals = 2, currency = '') {
  if (value === undefined) {
    return ''
  }

  if (!value) {
    return value
  }

  if (!isFinite(value) || (!value && value !== 0)) {
    return ''
  }

  value = parseFloat(value)

  // currency = currency != null ? currency : '¥'
  // decimals = decimals != null ? decimals : 2

  var stringified = Math.abs(value).toFixed(decimals)
  var _int = decimals ? stringified.slice(0, -1 - decimals) : stringified

  var i = _int.length % 3
  var head = i > 0 ? (_int.slice(0, i) + (_int.length > 3 ? ',' : '')) : ''
  var _float = decimals ? stringified.slice(-1 - decimals) : ''
  var sign = value < 0 ? '-' : ''

  return sign + currency + head + _int.slice(i).replace(/(\d{3})(?=\d)/g, '$1,') + _float
}


>> 留言评论