paper123
paper123

Reputation: 99

Format two separate string dates in JS

I have two dates that are in the following format in a single string "03.09.2020 – 08.11.2020", I would need to separate these two dates in to 6 different variables:

startDay, startMonth, startYear, endDay, endMonth, endYear

What would be the best way to go about this? a for loop? performance wise

Upvotes: 1

Views: 66

Answers (4)

GMKHussain
GMKHussain

Reputation: 4719

SIMPLY do this for functional purpose create function and pass your date range value into parameter function will return global variable SEE EXAMPLE

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}`)

Upvotes: 1

Sergio Vargas
Sergio Vargas

Reputation: 16

I would do it this way:

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})

Upvotes: 0

Brian Lee
Brian Lee

Reputation: 18197

Using split and some array desctructuring:

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}`)

Upvotes: 2

Alan Omar
Alan Omar

Reputation: 4227

you can use the following approach:

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);

Upvotes: 1

Related Questions