在 JS 中格式化两个单独的字符串日期

Format two separate string dates in JS

我在一个字符串中有两个采用以下格式的日期 "03.09.2020 – 08.11.2020",我需要将这两个日期分成 6不同的变量:

开始日、开始月、开始年、结束日、结束月、结束年

解决此问题的最佳方法是什么?一个for循环?性能明智

您可以使用以下方法:

let str = "03.09.2020 - 08.11.2020".replace(" - ",'.') // replace the ` - ` whith `.`
let [startDay, startMonth, startYear, endDay, endMonth, endYear] = str.split('.') //use array destructuring to initilze the variables

console.log(startDay, startMonth, startYear, endDay, endMonth, endYear);

使用split和一些数组解构:

const initial = '03.09.2020 – 08.11.2020'

const [ start, end ] = initial.split('–')
const [ startDay, startMonth, startYear ] = start.split('.')
const [ endDay, endMonth, endYear ] = end.split('.')

console.log(`startDay: ${startDay}`)
console.log(`startMonth: ${startMonth}`)
console.log(`startYear: ${startYear}`)
console.log(`endDay: ${endDay}`)
console.log(`endMonth: ${endMonth}`)
console.log(`endYear: ${endYear}`)

我会这样做:

const string = '03.09.2020 – 08.11.2020'

const dates = string.split( '– ').map(date => date.split('.'))

const startDay= dates[0][0]
const startMonth= dates[0][1]
const startYear= dates[0][2]
const endDay= dates[1][0]
const endMonth= dates[1][1]
const endYear = dates[1][2]

console.log({startDay, startMonth, startYear, endDay, endMonth, endYear})

简单地出于功能目的执行此操作创建函数并将您的日期范围值传递给参数函数将return全局变量参见示例

let dateRange = "03.09.2020 - 08.11.2020";


function dateFunc(x){
  
  let y = x.replace(' - ', ".")
  
  return  [startDay, startMonth, startYear, endDay, endMonth, endYear] = y.split('.')
  /* returning global variables which can accessible outside of function*/
  
}


dateFunc(dateRange) /* Pass you date range value */

console.log (`Start Date: ${startDay} ${startMonth}  ${startYear}`)

console.log (`End Date: ${endDay} ${endMonth}  ${endYear}`)