js中将时间转换为指定格式(‘yyyy-MM-DD)的字符串

/**
 * 转换时间 MM-DD
 * @param dateTime 时间戳
 * @param type 时间格式
 */
export function timetrans(dateTime: any, type: string) {
  const date = new Date(dateTime)
  var Y = date.getFullYear() + '-'  // 获取年份,后面加上'-'
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'  // 获取月份,如果小于10则在前面加上'0',后面加上'-'
  var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ''  // 获取日期,如果小于10则在前面加上'0'
  var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'  // 获取小时,如果小于10则在前面加上'0',后面加上':'
  var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'  // 获取分钟,如果小于10则在前面加上'0',后面加上':'
  var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()  // 获取秒钟,如果小于10则在前面加上'0'

  if (type == 'yyyy-MM-DD') {  // 如果传入的type为'yyyy-MM-DD',返回年-月-日格式的字符串
    return Y + M + D
  } else {  // 否则返回月-日格式的字符串
    return M + D
  }
}

猜你喜欢

转载自blog.csdn.net/qq_28838891/article/details/131467324