libs/tools.js stringToDate dateToString 日期字符串转换函数

libs/tools.js stringToDate dateToString 日期字符串转换函数

import { stringToDate } from '@/libs/tools.js'
 
export const stringToDate = (dateStr, separator) => {
  if (!separator) {
    separator = '-'
  }
  let dateArr = dateStr.split(separator)
  let year = parseInt(dateArr[0])
  let month
  // 处理月份为 04 这样的情况
  if (dateArr[1].indexOf('0') === 0) {
    month = parseInt(dateArr[1].substring(1))
  } else {
    month = parseInt(dateArr[1])
  }
  let day = parseInt(dateArr[2])
  let date = new Date(year, month - 1, day)
  return date
}

export const dateToString = (date, separator) => {
  if (!separator) {
    separator = '-'
  }
  let year = date.getFullYear()
  let month = (date.getMonth() + 1).toString()
  let day = (date.getDate()).toString()
  if (month.length === 1) {
    month = '0' + month
  }
  if (day.length === 1) {
    day = '0' + day
  }
  var dateTime = year + separator + month + separator + day
  return dateTime
}

 

posted @ 2019-04-03 13:51  彭成刚  阅读(262)  评论(0编辑  收藏  举报