js获取时间处理年月日/ 时分秒

// 获取时间,格式YYYY-MM-DD
export function getFormatDate (type) {
  const date = new Date()
  const year = date.getFullYear()
  let month = date.getMonth() + 1
  let strDate = ''
  const seperator1 = '-' // 连接年月日
  const seperator2 = ':' // 连接时分秒
  let currentdate = ''
  strDate = date.getDate()
  if (month >= 1 && month <= 9) {
    month = '0' + month
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = '0' + strDate
  }
  switch (type) {
    case 'date':
      currentdate = year + seperator1 + month + seperator1 + strDate
      break
    case 'time':
      currentdate = date.getHours() + seperator2 + date.getMinutes() + seperator2 + date.getSeconds()
      break
    case 'year':
      currentdate = parseInt(year)
      break
    default:
      return false
  }
  return currentdate
}
// 获得年、月、日、时、分、秒
// 返回值是如果是个位,用0补位,返回值是字符串格式
export function getTime (type) {
  var date = new Date()
  var time = null
  switch (type) {
    case 'year':
      time = date.getFullYear().toString()
      break
    case 'month':
      time = date.getMonth() + 1
      time = time.toString().length === 2 ? time : ('0' + time)
      break
    case 'day':
      time = date.getDate()
      time = time.toString().length === 2 ? time : ('0' + time)
      break
    case 'hour':
      time = date.getHours()
      time = time.toString().length === 2 ? time : ('0' + time)
      break
    case 'minute':
      time = date.getMinutes()
      time = time.toString().length === 2 ? time : ('0' + time)
      break
    case 'second':
      time = date.getSeconds()
      time = time.toString().length === 2 ? time : ('0' + time)
      break
  }
  return time
}
原文地址:https://www.cnblogs.com/litterjoan/p/10619942.html