Bootstrap

JS时间转换,标准时间标准时间<==>年月日年月日;时间戳<==>年月日等等

1、将标准时间转换为年月日

const standardTimeToYYMMDD = timeStr => {
  // 将时间字符串转换为Date对象
  var date = new Date(timeStr)
  // 提取年、月、日
  var year = date.getFullYear()
  var month = ('0' + (date.getMonth() + 1)).slice(-2)
  var day = ('0' + date.getDate()).slice(-2)
  // 拼接年月日字符串
  var ymdStr = year + '-' + month + '-' + day
  // 返回年月日字符串
  return ymdStr
}

2、将年月日转换为标准时间

const YYMMDDToStandardTime = dateString => {
  const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = months[date.getMonth()]
  const day = days[date.getDay()]
  const hours = date.getHours()
  const minutes = date.getMinutes()
  const seconds = date.getSeconds()

  const formattedDate = `${day} ${month} ${date.getDate()} ${year} ${hours}:${minutes}:${seconds} GMT+0800 (中国标准时间)`
  return formattedDate
}

3、将时间戳转换为年月日

const timeStampToYYMMDD = timestamp => {
  var date = new Date(timestamp)
  var year = date.getFullYear()
  var month = ('0' + (date.getMonth() + 1)).slice(-2)
  var day = ('0' + date.getDate()).slice(-2)
  return year + '-' + month + '-' + day
}

4、将年月日转换为时间戳

const YYMMDDToTimeStamp = dateString => {
  var dateParts = dateString.split('-')
  var year = parseInt(dateParts[0])
  var month = parseInt(dateParts[1]) - 1 // 月份从 0 开始
  var day = parseInt(dateParts[2])
  var timestamp = new Date(year, month, day).getTime()
  return timestamp
}

5、获取今天的年月日

const getTodayYYMMDD = () => {
  const today = new Date()
  const year = today.getFullYear()
  const month = String(today.getMonth() + 1).padStart(2, '0')
  const day = String(today.getDate()).padStart(2, '0')
  const str = year + '-' + month + '-' + day
  return str
}

6、是否在今天前

const isTodayBefore = dateStr => {
  const date = new Date(dateStr)
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return date >= today
}

7、获取两个日期之间的日期

const getDatesBetween = (startDate, endDate) => {
  let dates = []
  let currentDate = new Date(startDate)
  let endDate = new Date(endDate)
  while (currentDate < endDate) {
    let dateString = currentDate.toISOString().substr(0, 10)
    dates.push(dateString)
    currentDate.setDate(currentDate.getDate() + 1)
  }
  return dates
}

;