i'm doing a program which, given the day of the year, estabilishes day and month.
I wrote this code, but it doesn't work when the input is >31.
I hope that someone will help me, thank you.
<script>
var dayn=[31,28,31,30,31,30,31,31,30,31,30,31];
var vettmonth=["January", "February", "March", "April", "May","June","July","August","September","October","November","Dicember"];
function f()
{
var nday, day, month, count=0;
nday=eval(ngiorno.value);
for(var i=0;i<12;i++){
if (nday>dayn[i]){
count=count+dayn[i]; }
else if(nday<32){
day=nday;
month=vettmonth[i];
break;
}
else if(nday>31 && nday<dayn[i+1]+count){
day=nday-count;
month=vettmonth[i+1];
break;
}
}
mmese.value=month;
ggiorno.value=day;
}
</script>
The problem is that you're never reducing nday as you go through the months. So if nday > 31, nday > dayn[i] will be true every time, and you'll never execute the else if blocks that set day and month. You need to subtract dayn[i] from nday.
There's no need for two else if blocks. When the if block fails you're in the correct month. And the count variable is not needed, either.
var dayn = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var vettmonth = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
function f(nday) {
var day, month;
var daynum = nday;
for (var i = 0; i < dayn.length; i++) {
if (nday > dayn[i]) {
nday -= dayn[i];
} else {
day = nday;
month = vettmonth[i];
break;
}
}
console.log(`${daynum} = ${month} ${day}`);
}
f(10)
f(32);
f(150);
f(360);
You've made this more complicated then it has to be. You can do something like this:
const vettmonth=["January", "February", "March", "April", "May","June","July","August","September","October","November","Dicember"];
let dayOfTheYear = 120;
let date = new Date(new Date().getFullYear(), 0, 1); // Start of this year
date.setDate(120); // increase the date by "dayOfTheYear"
console.log("Month:",vettmonth[date.getMonth()], "Day:", date.getDate());
If you need to do this without using Date objects, you can do it like this:
const dayn = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
const vettmonth = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
let dayOfTheYear = 120;
let monthIndex = 0;
let day = 0;
for(let i = 0, sum = 0; i < dayn.length; i++){
sum+=dayn[i];
if(dayOfTheYear <= sum){
monthIndex = i;
day = (sum - dayOfTheYear) + 1;
break;
}
}
console.log("Month:", vettmonth[monthIndex], "Day:", day);
Related
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");
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)
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...
Can you please take a look at this demo and let me know how I can dynamically populate the number of each month for current year in jQuery or JavaScript?
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var daysInMonth = [];
var d = new Date();
var n = d.getMonth();
for (var i = 0; i < monthNames.length; i++) {
daysInMonth.push(d.getMonth());
}
console.log(daysInMonth);
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var daysInMonth = [];
for (var i = 0; i < monthNames.length; i++) {
var year = 2014;
var month = new Date(monthNames[i] + " 01 "+ year).getMonth() + 1;
daysInMonth.push(new Date(year, month, 0).getDate());
}
console.log(daysInMonth);
DEMO http://jsfiddle.net/0mj2cxmt/7/
#Sam Battat's answer works too, but for a simple snippet of code that works on any year when called you could try this:
var thisDay = new Date();
var thisYear = thisDay.getYear();
var feb29th = new Date(thisYear, 1, 29);
var febDays = ((feb29th.getMonth() === 1) ? 29 : 28);
var dayCounts = [31,febDays,31,30,31,30,31,31,30,31,30,31];
Notes:
The number of days is hard coded for all months except February since they don't change
The feb29th variable above will actually become March 1st on years that don't have 29 days (e.g. non-leap years) and thus the month won't be "1"... defaulting the number of days back to 28
Update:
After running this perf test http://jsperf.com/leap-year-check it has become apparent that the "crafty" check for a leap year performance is nowhere near as good as basic math checks.
Thus I'd consider this to be even more efficient.
var thisDay = new Date();
var thisYear = thisDay.getYear();
var febDays = 28;
if((thisYear % 4 == 0) && (thisYear % 100 != 0) || (thisYear % 400 == 0)){
febDays = 29;
}
var dayCounts = [31,febDays,31,30,31,30,31,31,30,31,30,31];
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'));