日期時間格式或封裝,已經互相轉換,抽出來往後方便本身開發,以前用做在mpvue的框架開發小程序中

// 時間格式化
export const dateFormat = (date, string) => {
  date = new Date(date)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  if (string == "YYYY年") {
    return [year].map(formatNumber).join('年') + '年'
  } else if (string == "YYYY/MM/DD") {
    return [year, month, day].map(formatNumber).join('/')
  } else if (string == "YYYY/MM/DD HH:MM") {
    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute].map(formatNumber).join(':')
  } else if (string == "YYYY.MM.DD HH:MM") {
    return [year, month, day].map(formatNumber).join('.') + ' ' + [hour, minute].map(formatNumber).join(':')
  } else if (string == "MM/DD") {
    return [month, day].map(formatNumber).join('/')
  } else if (string == "MM月DD日") {
    return [month, day].map(formatNumber).join('月') + '日 '
  } else if (string == "MM月DD日 HH:MM") {
    return [month, day].map(formatNumber).join('月') + '日 ' + [hour, minute].map(formatNumber).join(':')
  } else if (string == "MM-DD HH:MM") {
    return [month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber).join(':')
  } else if (string == "YYYY-MM-DD") {
    return [year, month, day].map(formatNumber).join('-')
  } else if (string == "YYYY.MM.DD") {
    return [year, month, day].map(formatNumber).join('.')
  } else if (string == "YYYY年MM月DD日 HH:MM") {
    return [year].map(formatNumber).join('年') + '年' + [month, day].map(formatNumber).join('月') + '日 ' + [hour, minute].map(formatNumber).join(':')
  } else if (string == "YYYY年MM月DD日") {
    return [year].map(formatNumber).join('年') + '年' + [month, day].map(formatNumber).join('月') + '日 '
  } else if (string == "HH:MM") {
    return [hour, minute].map(formatNumber).join(':')
  } else if (string == "HH:MM:SS") {
    return [hour, minute, second].map(formatNumber).join(':')
  } else {
    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  }
}
const formatNumber = n => {
// 主要用做判斷是否在個位數的時候 前面添加一個0 n
= n.toString() return n[1] ? n : '0' + n } // 日期格式轉換成時間戳 export const timeToTimestamp = (date, time) => { let dateStr = new Date(date + ' ' + time) return dateStr.getTime() }

想要用的時候 複製粘貼就行了spa

相關文章
相關標籤/搜索