-1

i have a string as Date between March 2018 and June 2018.
Now i am getting march 2018 and June 2018 in 2 variables.Now i want o/p as

March 2018
April 2018
May 2018
June 2018

CODE:

var temp="Date between March 2018 and June 2018";
var fields=temp.split(' ');
var date2=fields[fields.length-2] +" "+fields[fields.length-1];

var date1=fields[fields.length-5] +" "+fields[fields.length-4];
alert(date1);//March 2018
alert(date2);//June 2018
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
Deepak Jain
  • 137
  • 1
  • 3
  • 27
  • You can simply use for loop to find range between your months, `for(var i = new Date(date1).getMonth() + 1; i < new Date(date2).getMonth();i++) { console.log(i) }`. Then you can map `var i` to `month name` by defining `months` as array – nerding_it Jul 24 '18 at 06:24
  • If you don't use a plugin, you'll need an array of month names. Here's an example: https://stackoverflow.com/questions/1643320/get-month-name-from-date use that with `indexOf` to get the two month positions, then extrapolate. – freedomn-m Jul 24 '18 at 06:25
  • @sriharsha_bhat i am getting as 3,4 as the o/p not the o/p i want Month name along with yr – Deepak Jain Jul 24 '18 at 06:33
  • @Shrey I added updated code in answer – nerding_it Jul 24 '18 at 06:44
  • http://idownvotedbecau.se/noattempt/ while guidance has been given and mostly-complete answers provided, these should be expanded by OP to get their final solution. Instead OP is just adding new details to valid answers such as "need in an array" (not in the question) or "also need extremities" (not in question and the opposite of "between"). These do not affect the validity of the answers. – freedomn-m Jul 24 '18 at 07:33

5 Answers5

1

You can use moment.js for this:

const numberOfMonthsDiff = moment(date2).diff(moment(date1), 'months', true);

Documentation of the diff method.

By default, moment#diff will truncate the result to zero decimal places, returning an integer. If you want a floating point number, pass true as the third argument. Before 2.0.0, moment#diff returned a number rounded to the nearest integer, not a truncated number.

JSFIDDLE Example

Edit

I understand you want the months between:

var temp="Date between March 2018 and June 2018";
var fields=temp.split(' ');
var date2=fields[fields.length-2] +" "+fields[fields.length-1];
var date1=fields[fields.length-5] +" "+fields[fields.length-4];
const numberOfMonthsDiff = moment(date2).diff(moment(date1), 'months', true);

const dateToModify = moment(date1);
const monthsBetween = Array.from(Array(numberOfMonthsDiff)).map(i => dateToModify.add(1,'months').format('MMMM YYYY'));

JSFIDDLE Example

Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
1

If you want to get only the names of months between the two months in the string:

  • You first need to declare an array with the names of all months sorted.
  • Extract the two months from your string.
  • Get the indexes of your two months in the array of months.
  • Loop through the array between the two indexes and get the months.

This is how should be the code:

var temp = "Date between March 2017 and June 2018";
var dateStrings = temp.match(/(\w+\s\d{4})/gi);

const monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];
let index1 = monthNames.indexOf(dateStrings[0].split(" ")[0]);
let index2 = monthNames.indexOf(dateStrings[1].split(" ")[0]);
let year1 = dateStrings[0].split(" ")[1];
let year2 = dateStrings[1].split(" ")[1];

var diff = +year2 - +year1;
var results = [];
if (diff == 0) {
  for (var i = index1; i <= index2; i++) {
    results.push(monthNames[i] + " " + year1);
  }
} else {
  for (var i = index1; i < monthNames.length; i++) {
    results.push(monthNames[i] + " " + year1);
  }
  diff--;
  var year = +year1 + 1;
  for (var y = 0; y < diff; y++) {
    for (var i = 0; i < monthNames.length; i++) {
      results.push(monthNames[i] + " " + year);
    }
    year++;
  }
  for (var i = 0; i <= index2; i++) {
    results.push(monthNames[i] + " " + year2);
  }
}

Demo:

var temp = "Date between March 2016 and June 2018";
var dateStrings = temp.match(/(\w+\s\d{4})/gi);


const monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

let index1 = monthNames.indexOf(dateStrings[0].split(" ")[0]);
let index2 = monthNames.indexOf(dateStrings[1].split(" ")[0]);

let year1 = dateStrings[0].split(" ")[1];
let year2 = dateStrings[1].split(" ")[1];

console.log(+year2 - +year1);

var diff = +year2 - +year1;
var results = [];
if (diff == 0) {
  for (var i = index1; i <= index2; i++) {
    results.push(monthNames[i] + " " + year1);
  }
} else {
  for (var i = index1; i < monthNames.length; i++) {
    results.push(monthNames[i] + " " + year1);
  }
  diff--;
  var year = +year1 + 1;
  for (var y = 0; y < diff; y++) {
    for (var i = 0; i < monthNames.length; i++) {
      results.push(monthNames[i] + " " + year);
    }
    year++;
  }
  for (var i = 0; i <= index2; i++) {
    results.push(monthNames[i] + " " + year2);
  }
}

console.log(results);
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
1

maybe we need to take years into consideration too. :-) https://jsfiddle.net/z07rwmnL/17/

var months = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December"
]

var temp = "Date between March 2018 and June 2019";
var match = temp.match(/Date between (\S+) (\d+) and (\S+) (\d+)/);

if (match) {
  var fromMonth = match[1];
  var fromYear = parseInt(match[2], 10);
  var toMonth = match[3];
  var toYear = parseInt(match[4], 10);

  if (toYear >= fromYear) {
    var fromMonthIdx = months.indexOf(fromMonth);
    var toMonthIdx = months.indexOf(toMonth);

    while (toYear >= fromYear) {
      var endIdx = (toYear > fromYear) ? 12 : toMonthIdx;
      for (var i = fromMonthIdx + 1; i < endIdx; i++) {
        console.log(months[i] + " " + fromYear);
      }
      fromMonthIdx = -1;
      fromYear++;
    }
  }
}
D. Seah
  • 4,472
  • 1
  • 12
  • 20
1

You can simply use for loop for getting range in between months,

var monthNames = [ "January", "February", "March", "April", "May", "June", 
                       "July", "August", "September", "October", "November", "December" ];
                       var temp="Date between March 2018 and June 2018";
var fields=temp.split(' ');
var date2=fields[fields.length-2] +" "+fields[fields.length-1];

var date1=fields[fields.length-5] +" "+fields[fields.length-4];
for(var i = new Date(date1).getMonth(); i <= new Date(date2).getMonth();i++) {
    console.log(monthNames[i])
}
nerding_it
  • 704
  • 7
  • 17
  • how to get march and June also in the o/p – Deepak Jain Jul 24 '18 at 07:17
  • @Shrey you **really** need to do *some* work yourself. Just remove the `+1` and change `i <` to `i <=`. However your question was months *between* where between does not include the limits (as they are not "between"). – freedomn-m Jul 24 '18 at 07:30
  • sir i am not getting yr here – Deepak Jain Jul 24 '18 at 07:33
  • @Shrey I changed the condition in for loop, Basically I removed +1 so it starts from `date1` and I put `<=` instead of `<` so it will loop till `date2`. This should give solution for your problem – nerding_it Jul 24 '18 at 07:49
1

I think you can use regular expression to find two date boundary, and then loop through it for the expected output. Note that this solution cater cross year (no exception handling, it assumed your input string is in constant format).

var str = "Date between March 2017 and June 2018"; 
var startRE =  /between (.*) and/g;
var endRE =  /and (.*)/g;
var start = startRE.exec(str);
var end = endRE.exec(str);
var startDate = start[1]
var endDate = end[1]

var startMonth = startDate.split(' ')[0]
var startYear = startDate.split(' ')[1]

const monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

var endMonth = endDate.split(' ')[0];
var endYear = endDate.split(' ')[1];
for(var y=startYear;y<=endYear; y++){
    if(y==endYear){
        if(startYear==endYear)
          for(var m=monthNames.indexOf(startMonth);m<monthNames.indexOf(endMonth)-1;m++){
              console.log("Output:"+monthNames[m] + " " + y);
          }
        else
          for(var m=0;m<monthNames.indexOf(endMonth);m++){
              console.log("Output:"+monthNames[m] + " " + y);
          }
    }
    else{
        if(y=startYear)
        for(var m=monthNames.indexOf(startMonth);m<12;m++){
          console.log("Output:"+monthNames[m] + " " + y);
        }
        else
        {
          for(var m=0;m<12;m++){
            console.log("Output:"+monthNames[m] + " " + y);
          }
        }
    }
}
SKLTFZ
  • 841
  • 2
  • 10
  • 30