【微信小程序】mpvue中格式化日期

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shine_a/article/details/88174499

1、修改src/utils/index.js文件

mpvue框架中有一个专门格式化日期的文件src/utils/index.js文件
文件内容如下,其中formatDate是我自己添加的方法,是将日期格式化成“YYYY-mm-DD”格式。注意不要忘记在export default {}中添加formatDate,不然外部问件读取不到这个方法

function formatNumber (n) {
  const str = n.toString()
  return str[1] ? str : `0${str}`
}

export function formatTime (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()

  const t1 = [year, month, day].map(formatNumber).join('/')
  const t2 = [hour, minute, second].map(formatNumber).join(':')

  return `${t1} ${t2}`
}

export function formatDate (date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  
  const t1 = [year, month, day].map(formatNumber).join('-')
  return t1
}

export default {
  formatNumber,
  formatTime,
  formatDate
}

2、在vue文件中引入utils/index.js文件

代码示例:

export default {
  data () {
    var util = require('../../utils/index.js')
    return {
      date:util.formatDate(new Date)
    }
  }
}

其中date就代表今天的日期2019-03-05

猜你喜欢

转载自blog.csdn.net/shine_a/article/details/88174499
今日推荐