Home > database >  Js return the start date and end date on a string
Js return the start date and end date on a string

Time:03-02

I have strings like this:

(Feb 28-Mar 1)
(Mar 2-3)

I would like me to return an object as you can see below, someone to give some suggestion how can I do?

    function rD(text){
    let date = text.replace('(', '').replace(')', '').split(' ');
    //const [start, end] = date[2].split("-").map(Number);
    return date;
    }
    
    
    console.log(rD("(Feb 28-Mar 1)"))
    console.log(rD("(Mar 2-3)"))

Return:

[
{
  month: 2,
  day: 28
},
{
  month: 3,
  day: 1
}
]

[
{
  month: 3,
  day: 2
},
{
  month: 3,
  day: 3
}
]

CodePudding user response:

I'd remove the parentheses first and then split by /[ -]/. This way you get an array in one of these two forms

["Feb", "28", "Mar", "1"]

or

["Mar", "2", "3"]

Now if the array has 4 elements the first and third are always the month and second and forth are the day. If the array has 3 elements, the first is a month for both, start and end, the second and third are the days.

For getting the number of the month you can have a simple lookup like

{ Jan:1, Feb:2, ... }

CodePudding user response:

You can try this

function rangeCalcFunc(range = null) {
  if(range && range.length){
    const [start, end] = range.substring(1, range.length-1).split("-");
    console.log(start);console.log(end);
    const [startMon, startDt] = start.split(" ");
    const [endMon, endDt] = end.split(" ");
    
    return [
    {
      month: calcMonthInNumber(startMon.trim()),
      date: startDt
    },
    {
      month: calcMonthInNumber(endMon.trim()),
      date: endDt
    }
    ]
  }
}

function calcMonthInNumber(month) {
    switch(month.toLowerCase()){
      case 'jan': return '01'
      case 'feb': return '02'
      //add for other months
      default: break;
    }
}

console.log(rangeCalcFunc("(Jan 28-Feb 1)"));

CodePudding user response:

I'd suggest using a regex pattern to parse each span.

From this we can get the startMonth, startDay, endMonth, endDay. We can then create a getMonthNumber() function to turn the abbreviated month name (Jan, Feb, etc.) to a number.

function getMonthNumber(month) {
    const lookup = { jan: 01, feb: 02, mar: 03, apr: 04, may: 05, jun: 06, jul: 07, aug: 08, sep: 09, oct: 10, nov: 11, dec: 12};
    return lookup[(month   '').toLowerCase()]
}

function parseSpan(str) {
    const pattern = /\(([a-z]{3})\s (\d{1,2})\-([a-z]{3})?\s?(\d{1,2})\)/i
    const [, startMonth, startDay, endMonth, endDay] = str.match(pattern);
    return [
        { month: getMonthNumber(startMonth), day:  startDay },
        { month: getMonthNumber(endMonth || startMonth), day:  endDay }
    ];
}

let testInputs = [
  '(Feb 28-Mar 1)',
  '(Mar 2-3)',
  '(Sep 28-Oct 31)',
  '(Jan 3-17)'
]

testInputs.map(parseSpan).forEach(span => console.log(span))
.as-console-wrapper { max-height: 100% !important; }

CodePudding user response:

First we are going to create a mapper for the months. like this:

let MonthsMapper = new Map([['Jan', 1], ['Feb', 2], ['Mar', 3] /*...*/])

Then we need a function which cutes the string into chunks by removing the parenthesis and splitting it by its hyphen. The first chunks are the start and end dates. With these two dates we can further get the start month, start day, end month, and end day. (By splitting our chunks by there whitespaces)

There is only one special case I can see from your example and that is the case when the end date does not specify a month, in which case it is implicitly the start month.

let DateObjectParser = (dateString) => {
    const [startDate, endDate] = dateString.replace(/[()]/g, '').split('-')
    const [startMonth, startDay] = startDate.split(' ')
    let [endMonth, endDay] = endDate.split(' ')

    // in case a second month is not provided
    if (endDay === undefined) {
        endDay = endMonth
        endMonth = startMonth
    }

    return [
       {
           month: MonthsMapper.get(startMonth),
           day: parseInt(startDay),
       },
       {
            month: MonthsMapper.get(endMonth),
            day: parseInt(endDay),
       }
  ]
}
  • Related