Johnny Metz
Johnny Metz

Reputation: 5975

Parse JavaScript date strings that may or may not contain the year

I need to parse date strings that may or may not have the year. Here are some examples:

# with year
s1 = '2020-01-01'
s2 = '2020-11-22'

# without year
s3 = '01-01'
s4 = '11-22'

The goal is to end up with the following objects:

obj1 = {'month': 1, 'day': 1, 'year': 2020}
obj2 = {'month': 11, 'day': 22, 'year': 2020}
obj3 = {'month': 1, 'day': 1}
obj4 = {'month': 11, 'day': 22}

Is there a simple way to parse this?

Upvotes: 0

Views: 45

Answers (2)

RobG
RobG

Reputation: 147413

Just split into parts and return an appropriate object based on whether there's a year or not, e.g.

function parseSpecial(s) {
  let [a, b, c] = s.split(/\D/);
  return c? {day: +c, month: +b, year:+a} :  {day: +b, month:+a};
}

['2020-01-01',
 '2020-11-22',
 '01-01',
 '11-22'
].forEach(s => console.log(parseSpecial(s)));

Upvotes: 0

GirkovArpa
GirkovArpa

Reputation: 4912

This is the function you need:

dates.reduce((obj, date, i) => {
  const [day, month, year] = date.match(/\d+/g).reverse().map(Number);
  obj['obj' + ++i] = year ? { day, month, year } : { day, month };
  return obj;
}, {});

Here's a live example:

'use strict';

const dates = ['2020-01-01', '2020-11-22', '01-01', '11-22'];

const result = dates.reduce((obj, date, i) => {
  const [day, month, year] = date.match(/\d+/g).reverse().map(Number);
  obj['obj' + ++i] = year ? { day, month, year } : { day, month };
  return obj;
}, {});

console.log(result);

/*
{
  obj1: { day: 1, month: 1, year: 2020 },
  obj2: { day: 22, month: 11, year: 2020 },
  obj3: { day: 1, month: 1 },
  obj4: { day: 22, month: 11 }
}
*/

Upvotes: 1

Related Questions