util.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import moment from 'moment'
  2. export const formatTime = (date: Date) => {
  3. const year = date.getFullYear()
  4. const month = date.getMonth() + 1
  5. const day = date.getDate()
  6. const hour = date.getHours()
  7. const minute = date.getMinutes()
  8. const second = date.getSeconds()
  9. return (
  10. [year, month, day].map(formatNumber).join('/') +
  11. ' ' +
  12. [hour, minute, second].map(formatNumber).join(':')
  13. )
  14. }
  15. /// 格式化日期
  16. export function formatDate(date: Date) {
  17. date = new Date(date);
  18. return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  19. }
  20. /**
  21. * 日期格式化
  22. * @param value
  23. * @param format
  24. * @returns
  25. */
  26. export function formatDateString(value?: string, format = 'YYYY-MM-DD HH:mm:ss') {
  27. if (value) {
  28. return moment(value).format(format)
  29. }
  30. return handleNoneValue()
  31. }
  32. /**
  33. * 处理空值的情况
  34. * @param value 值
  35. * @param suffix 后缀名
  36. * @returns
  37. */
  38. export function handleNoneValue<T>(value?: T, suffix = '') {
  39. if (value == null || String(value) === '') {
  40. return '--'
  41. }
  42. return value + suffix
  43. }
  44. const formatNumber = (n: number) => {
  45. const s = n.toString()
  46. return s[1] ? s : '0' + s
  47. }
  48. /// 判断字符串是否为空
  49. export const isnullstr = (str: string) => {
  50. return str == '' ? '--' : str
  51. }
  52. /// 截取两位小数位
  53. export const getDecimalNum = (number: string) => {
  54. let amount = number
  55. let num = null
  56. // 小数点后最多只能输入两位
  57. num = number.replace(new RegExp('^(\\d+\\.\\d{2}).+'), '$1')
  58. // 小数点开头得话,让前面加个0 eg: 0.xx
  59. const startPoint = /^\./g
  60. if (startPoint.test(num)) { num = amount.replace(startPoint, '0.') }
  61. // 若没有小数点,前面输入多个0,去掉0取整
  62. // if(num有值 && 没有小数点 && 不等于'0')
  63. if (num && !num.includes('.') && num !== '0') { num = +num }
  64. // 若出现多个小数点,则替换为1个
  65. const morePoint = /\.+(\d*|\.+)\./g
  66. if (morePoint.test(String(num))) {
  67. num = amount
  68. .replace(/\.{2,}/g, ".")
  69. .replace(".", "$#$")
  70. .replace(/\./g, "")
  71. .replace("$#$", ".")
  72. }
  73. return num
  74. }