get month names between 2 dates - javascript

I have to two dates from and to. I want to get all of the month names between these two dates.
Following is my code
var monthNames = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];
function diff(from, to) {
var datFrom = new Date('1 ' + from);
var datTo = new Date('1 ' + to);
var arr = monthNames.slice(datFrom.getMonth(), datTo.getMonth() + 1);
}
above code works for following inputs
diff('September 2013', 'December 2013');
but it does not work for this
diff('September 2013', 'February 2014');
How can I make it work?

Mine is better: http://jsfiddle.net/kS73f/8/
var monthNames = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];
function diff(from, to) {
var arr = [];
var datFrom = new Date('1 ' + from);
var datTo = new Date('1 ' + to);
var fromYear = datFrom.getFullYear();
var toYear = datTo.getFullYear();
var diffYear = (12 * (toYear - fromYear)) + datTo.getMonth();
for (var i = datFrom.getMonth(); i <= diffYear; i++) {
arr.push(monthNames[i%12] + " " + Math.floor(fromYear+(i/12)));
}
return arr;
}
console.log(diff('September 2013', 'March 2014'));

You're going to have to do a more manual method than slice. Here's a starting point you can determine how to handle cases as mentioned in comments.
function diff(from, to) {
var result = [];
var datFrom = new Date('1 ' + from);
var datTo = new Date('1 ' + to);
if(datFrom < datTo) {
var month = datFrom.getMonth();
var toMonth = datTo.getMonth() + 1 + ((datTo.getYear() - datFrom.getYear())*12); //toMonth adjusted for year
for(; month < toMonth; month++) { //Slice around the corner...
result.push(monthNames[month % 12]);
}
}
return result;
}
diff('September 2013', 'February 2014'); //=["September", "October", "November", "December", "January", "February"]

var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
function diff(from, to) {
var datFrom = new Date('1 ' + from);
var datTo = new Date('1 ' + to);
var arr;
if(datFrom > datTo) {
return diff(to, from);
}
var fromYear = datFrom.getFullYear();
var toYear = datTo.getFullYear();
if(fromYear === toYear) {
return monthNames.slice(datFrom.getMonth(), datTo.getMonth() + 1);
} else {
var arr = addYear(monthNames.slice(datFrom.getMonth(), new Date('1 December ' + fromYear)), fromYear);
for(var i = 1; i < (toYear - fromYear); i++) {
arr = arr.concat(addYear(monthNames, fromYear + i));
}
return arr.concat(addYear(monthNames.slice(new Date('1 January ' + fromYear).getMonth(), datTo.getMonth() + 1), toYear));
}
}
function addYear(arr, year) {
var updatedArr = [];
for(var i = 0; i < arr.length; i++) {
updatedArr[i] = arr[i] + ' ' + year;
}
return updatedArr;
}
Than try console.log(diff('September 2013', 'February 2015')) to test it.

The following modifies the original function as little as possible, if that helps the OP from a comprehension standpoint.
function diff(from, to) {
var datFrom = new Date('1 ' + from);
var datTo = new Date('1 ' + to);
var arr = monthNames.slice(datFrom.getMonth(), datTo.getMonth() + 1);
if (!arr.length) {
arr = monthNames.slice(datFrom.getMonth(), 12);
arr = arr.concat(monthNames.slice(0, datTo.getMonth() + 1));
}
return arr;
}
console.log(diff('December 2013', 'February 2014')); //["September", "October", "November", "December", "January", "February"]

Lazy answer:
var monthNames = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December",
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];
function diff(from, to) {
var mFrom = new Date('1 ' + from).getMonth();
var mTo = new Date('1 ' + to).getMonth();
mTo = mTo < mFrom ? mTo + 12 : mTo;
return monthNames.slice(mFrom, mTo + 1);
}
alert(diff('September 2013', 'December 2013'));
alert(diff('September 2013', 'February 2014'));

Related

Format array elements from one form to another -JS

I have an array of strings that are actually dates in the form of 201001 ,201002. I would like to convert those array items to something like 2010 January, 2010 February. Is there any way to do this.
var Array = ["201005", "201006", "201007", "201008", "201009", "201010", "201011", "201012", "201101", "201102", "201103", "201104", "201106", "201107", "201108", "201109", "201110", "201111", "201112", "201201", "201202", "201203", "201204", "201205", "201206", "201207", "201208", "201209", "201210", "201211", "201212", "201301", "201302", "201303", "201304", "201305", "201306", "201307"];
I'm looking for an array like :
var expected = ["2010 january", "2010 February" etc]
You could do this:
const monthMap = {
"01": "January",
"02": "February",
"03": "March",
"04": "April",
"05": "May",
"06": "June",
"07": "July",
"08": "August",
"09": "September",
"10": "October",
"11": "November",
"12": "December"
};
xAxisArray = xAxisArray.map(axis => {
const year = axis.substring(0, 4);
const month = axis.substring(4, 6);
return `${year} ${monthMap[month]}`;
});
Or you could use moment, but that might be overkill.
You can try my code
function formatDate(date) {
var monthNames = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
var monthIndex = date.getMonth();
var year = date.getFullYear();
return year + ' ' + monthNames[monthIndex];
}
var result = xAxisArray.map(item => {
var strDate = item.slice(0, 4) + '-' + item.slice(4, 6) + '-01'
return formatDate(new Date(strDate))
})
console.log(result)
This is a demo: https://codepen.io/phuongnm153/pen/xxKgKYp
You can try the following code:
var xAxisArray = ["201005", "201006", "201007", "201008", "201009", "201010", "201011", "201012", "201101", "201102", "201103", "201104", "201106", "201107", "201108", "201109", "201110", "201111", "201112", "201201", "201202", "201203", "201204", "201205", "201206", "201207", "201208", "201209", "201210", "201211", "201212", "201301", "201302", "201303", "201304", "201305", "201306", "201307"];
//Array to link month number to name
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
//Result array
var formattedArray = [];
//Loop through the old array and push the formatted date to the new array
xAxisArray.forEach(function(element) {
var formatted = element.substr(0,4) + '-' + element.substr(4); //Add the dash between year and month
var date = new Date(formatted); //Create date object
var year = date.getFullYear(); //Get the year
var month = date.getMonth(); //Get the month
formattedArray.push(year + ' ' + monthNames[month]);
});
console.log(formattedArray);
First, create a date from the string. Then convert that date to the desired format and last add the new formatted string to a new array.
If you want to have the full name of the month, and not just the first three letter, you need to have them somewhere, for example:
const MONTHS = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
Then you can simply have:
const format = (value) => {
// assuming the format is 4 digits followed by 2 digits
const [, year, month] = value.match(/(\d{4})(\d{2})/);
return `${year} ${MONTHS[month - 1]}`
}
Then you can map your array such as:
const expected = xAxisArray.map(format);
Hope it helps!
You can get your answer by following approach .
xAxisArray.forEach(function(value , index){
var last2 = value.slice(-2);
const date = new Date(value.slice(4), last2); // 2009-11-10
const month = date.toLocaleString('default', { month: 'long' });
xAxisArray[index] = value.substring(0,4) +" "+ month;
});
Your problem will get solve .
You can use moment library for this:
const result = xAxisArray.map(item => {
const year = item.substring(0,4)
const month = item.substring(4,2)
return moment(`01/${month}/${year}`).format('YYYY MMMM')
})
console.log(result)
By using moment.js libary you can convert , use below expression convert it
moment("your value").format("YYYY MMM");
ex:moment(201005).format("YYYY MMM");

Display Current date with additional 30 days of calculation - JS

I am trying to display current date by finding string and replacing with current date, its working fine, but additionally I want to display another date where if string has some comma seprated value then it will add to the current date and will display accodrdingly, So lets say if I add (,30) in string it will add 30 days additional in current date and display
var setCurrentDate = function() {
var disclaimerStr = $(".dynamic-date").html(),
currDateStr = "{currentdate}",
date = new Date(),
months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
currDate =
months[date.getMonth()] +
" " +
date.getDate() +
", " +
date.getFullYear(),
newDisclaimerStr;
if (disclaimerStr.indexOf(currDateStr) != -1) {
newDisclaimerStr = disclaimerStr.replace(currDateStr, currDate);
$(".dynamic-date").html(newDisclaimerStr);
}
};
setCurrentDate();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dynamic-date">
<b>Current Date</b> : {currentdate} <br><br>
<b>Extended Date</b> : {currentdate,30} <br><br>
</div>
Try this code :
var setCurrentDate = function() {
var disclaimerStr = $(".dynamic-date").html(),
currDateStr = "{currentdate}",
date = new Date(),
months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
currDate =
months[date.getMonth()] +
" " +
date.getDate() +
", " +
date.getFullYear(),
newDisclaimerStr;
if (disclaimerStr.indexOf(currDateStr) != -1) {
newDisclaimerStr = disclaimerStr.replace(currDateStr, currDate);
$(".dynamic-date").html(newDisclaimerStr);
}
var reg = new RegExp(/\{currentdate(,(\d+))\}/);
var currDateStr2 = '{currentdate,30}'; // you need to change here!
var days = parseInt(reg.exec(currDateStr2)[2], 10);
console.log(days) //30
var date2 = new Date();
date2.setDate(date2.getDate() + days);
console.log(date2) // "2019-04-27T09:13:00.789Z"
};
setCurrentDate();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dynamic-date">
<b>Current Date</b> : {currentdate} <br><br>
<b>Extended Date</b> : {currentdate,30} <br><br>
</div>

problem while creating dynamic labels for chart js

I am creating dynamic labels for the chart js by supplying range of the month . It is working good if i selected start month and end month in ascending order but it is not working in the case where i selected start month = december and end month = march.
Here is my code ,
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthArr = [];
var monthn = ['December','March']; // here i give the lower and upper limit for the label
for (var i = monthNames.indexOf(monthn[0]); i <= monthNames.indexOf(monthn[1]); i++) {
monthArr.push(monthNames[i]);
}
return monthArr;
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthArr = [];
var monthn = ['December','March'];
if (monthNames.indexOf(monthn[1]) < monthNames.indexOf(monthn[0])) {
monthNames.unshift(monthNames.splice(monthNames.indexOf(monthn[0]), 1)[0]);
for (var i = monthNames.indexOf(monthn[0]); i <= diff; i++) {
monthArr.push(monthNames[i]);
}
} else {
for (var i = monthNames.indexOf(monthn[0]); i <= monthNames.indexOf(monthn[1]); i++) {
monthArr.push(monthNames[i]);
}
}
return monthArr;
Try to validate the index between the two months
Here is an example with your code and a very small changes.
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthArr = [];
var monthn = ['December','March']; // here i give the lower and upper limit for the label
// make sure that StartMonth is smaller then Endmonth
var startMonth = monthNames.indexOf(monthn[0]) <= monthNames.indexOf(monthn[1]) ? monthNames.indexOf(monthn[0]) : monthNames.indexOf(monthn[1]);
// make sure that EndMonth is bigger then StartMonth
var endMonth = monthNames.indexOf(monthn[0]) <= monthNames.indexOf(monthn[1]) ? monthNames.indexOf(monthn[1]) : monthNames.indexOf(monthn[0]);
for (var i = startMonth; i <= endMonth; i++) {
monthArr.push(monthNames[i]);
}
// Add the missing months
if (startMonth -1 >0)
{
for (var i = 0; i <= startMonth -1; i++) {
monthArr.push(monthNames[i]);
}
}
console.log(monthArr)

Assign value in for loop

I am trying to get the actual month from a loop. When I step through it in developer tools and month[i] == 4 it doesn't assign actualMonth to checkMonth
Do I have to assign getMonth to month[] and then try and query the value?
var showCurrentMonth = function() {
var getMonth = new Date().getMonth();
var month = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
var actualMonth = "";
for (var i = 0; i < month.length; i++) {
var checkMonth = month[i];
console.log(month[i]);
if (getMonth == month[i]) {
actualMonth = checkMonth;
}
}
console.log(actualMonth);
}
window.addEventListener('DOMContentLoaded', showCurrentMonth, false);
Too simple?
var showCurrentMonth = function() {
var getMonth = new Date().getMonth();
var month = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
var actualMonth = month[getMonth];
console.log(actualMonth);
}
window.addEventListener('DOMContentLoaded', showCurrentMonth, false);
Change your if to if (month[getMonth] == month[i]) {
Do it like this :
var showCurrentMonth = function() {
var getMonth = new Date().getMonth();
var month = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
var actualMonth = "";
for (var i = 0; i < month.length; i++) {
var checkMonth = month[i];
console.log(month[i]);
if (month[getMonth] == month[i]) { //Compare get month like this
actualMonth = checkMonth;
}
}
console.log(actualMonth);
}
window.addEventListener('DOMContentLoaded', showCurrentMonth, false);
Your problem is that you are comparing an integer and string:
var getMonth = new Date().getMonth(); // This return number from 0 to 11
The code Date().getMonth() returns an integer, and your month list has strings on it
Your code should be:
var showCurrentMonth = function() {
var getMonth = new Date().getMonth();
var month = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
var actualMonth = month[getMonth];
console.log(actualMonth);
}
window.addEventListener('DOMContentLoaded', showCurrentMonth, false);
To get the actual month you only need to access the month list with getMonth as index
slightly Modification required
var showCurrentMonth = function() {
var getMonth = new Date().getMonth();
console.log(getMonth);
var month = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
var actualMonth = "";
for (var i = 0; i < month.length; i++) {
var checkMonth = month[i];
if (getMonth == i) {
actualMonth = checkMonth;
}
}
console.log(actualMonth);
};
window.addEventListener('DOMContentLoaded', showCurrentMonth, false);

Create an array of number of occurrences from another array in Javascript

I have two array which looks like
var monthNames = [ "January", "January", "January", "April", "April", "December", "August", "August", "November", "November", "November", "December" ];
var monthRange = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];
Now I am wondering how should I work in JS so that I would get a new array back, again with 12 elements in it (one for each month) and get a count of it. So it will be like this -
[3, 0, 0, 2, 0, 0, 0, 2, 0, 0, 3, 1]
Here count is in the order of the monthRange which gives count for each month in monthNames .
So here
January : 3,
April: 2,
December: 1,
August: 2,
November: 3,
December : 1
This would do it:
var counts = monthRange.map(function(val) {
var count = 0;
for (var i = 0, j = monthNames.length; i < j; i++) {
if (val === monthNames[i]) count++;
}
return count;
});
You can map over the monthRange and then filter the monthNames to return the number of occurrences of each month:
monthRange.map(function(month) {
return monthNames.filter(function(n) { return n === month }).length;
});
Using underscore you can do it like this:
_.reduce(array, function(memo, month) {
memo[month] = (memo[month] === undefined ? 0 : memo[month]) + 1;
return memo
}, {})
In your case, it can look something like
var countMonths = function(array, m) {
return _.reduce(array, function(memo, month) {
memo[month] = (memo[month] === undefined ? 0 : memo[month]) + 1;
return memo
}, m)
}
var memo = countMonths(monthNames, {})
memo = countMonths(monthRange, memo)
Try Object to keep track of frequency:
var freq = function(list) {
var o = {};
var l = list.length;
var v;
while (v = list[--l])
o[v] = o[v] !== undefined ? o[v] + 1 : 1;
return o;
};
console.log(freq(["January", "January", "January", "April", "April", "December", "August", "August", "November", "November", "November", "December"]));
alert(JSON.stringify(freq(["apple", "mangoe", "apple"])));
Open console...

Categories

Resources