javascript获取各种格式字日期字符串

ppylox
·7/26/2021·0 阅读
AI 摘要模型根据正文自动生成,仅供参考

介绍一个JavaScript函数getDate(date, format),用于将日期格式化为多种字符串格式,支持YYYY、YYYY-MM、YYYY-MM-DD、YYYY-MM-DD HH:mm和HH:mm。函数在无参数时默认使用当前时间,对字符串日期中的横杠替换为斜杠以兼容IE11解析,并对月、日、时、分不足两位时补零。调用时传入日期和格式即可返回对应格式字符串。

/**

   * 获取各种格式字符串

   * 格式 YYYY-MM-DD HH:mm

   * @param {*} date

   * @param {*} format

   */

export function getDate(date, format) {

  let curDate = date

  let dateString = ''

  if (!curDate) {

    curDate = new Date()

  } else {

    // ie11下需将-替换成/,否则报错

    if (typeof (date) === 'string' && date.indexOf('-') !== -1) {

      date = date.replace(/-/g, '/')

    }

    curDate = new Date(date)

  }

  if (format === 'YYYY') {

    dateString = curDate.getFullYear()

  }

  if (format === 'YYYY-MM') {

    dateString = curDate.getFullYear() + '-' + (curDate.getMonth() + 1 < 10 ? '0' + (curDate.getMonth() + 1) : curDate.getMonth() + 1)

  }

  if (format === 'YYYY-MM-DD') {

    dateString = curDate.getFullYear() + '-' + (curDate.getMonth() + 1 < 10 ? '0' + (curDate.getMonth() + 1) : curDate.getMonth() + 1) + '-' + (curDate.getDate() < 10 ? '0' + curDate.getDate() : curDate.getDate())

  }

  if (format === 'YYYY-MM-DD HH:mm') {

    dateString = curDate.getFullYear() + '-' + (curDate.getMonth() + 1 < 10 ? '0' + (curDate.getMonth() + 1) : curDate.getMonth() + 1) + '-' + curDate.getDate() + ' ' + (curDate.getHours() < 10 ? '0' + curDate.getHours() : curDate.getHours()) + ':' + (curDate.getMinutes() < 10 ? '0' + curDate.getMinutes() : curDate.getMinutes())

  }

  if (format === 'HH:mm') {

    dateString = curDate.getHours() + ':' + (curDate.getMinutes() < 10 ? '0' + curDate.getMinutes() : curDate.getMinutes())

  }

  return dateString

}


调用的时候传入时间和格式,兼容ie,目前了解到ie11不能正常解析横杠,所以需要先处理成斜杠

getDate(date, "YYYY-MM-DD")

相关文章