how to get the days of 2,3,4 months in javascript - javascript

I want to get the days of more then 1 month if pass 2 , 3 ,4 as number of month to the function, I want to get total number of days from today
function get_days_in_month(months){
days_in_month = new Date();
var y = days_in_month.getFullYear();
var m = days_in_month.getMonth();
if(months==1){
return new Date(y,m+1,0).getDate();
}
if(months==2){
// need to write code or some other logic
}
}
Thanks for help in advance

Use a for loop:
var total = 0;
for (i = 1; i <= months; i++) {
total += new Date(y, m + i, 0).getDate();
}
return total;
JSFiddle demo.

Related

How to get current week date in javascript?

I have a problem getting the current week date in javascript. I wrote the following code to get the current week's date, It was working well but it seems it sometimes returns the next week's date. I could not understand where is the problem.
any help would be appreciated.
This is my code:
let curr = new Date();
let week = [];
for (let i = 1; i <= 7; i++) {
let first = curr.getDate() - curr.getDay() + i;
let day = new Date(curr.setDate(first)).toISOString().slice(0, 10);
week.push(day);
};
console.log(week)
The output:
['2022-06-13', '2022-06-14', '2022-06-15', '2022-06-16', '2022-06-17', '2022-06-18', '2022-06-19']
but today's date is 6/12/2022, but the above date started from 13/06/2022
Source:
here
When you do +i you are adding numbers 1 to 7 to your first variable. Now since the week starts from Sunday=0, you do not need to add an offset.
Just iterate loop from 0 to 6:
let curr = new Date(new Date().getTime() - (7 * 24 * 60 * 60 * 1000));
let week = [];
for (let i = 0; i < 7; i++) {
let first = curr.getDate() - curr.getDay() + i;
let day = new Date(curr.setDate(first)).toISOString().slice(0, 10);
week.push(day);
};
console.log(week)
[Edit] : If you want to get from 7 days ago, you can change how you initialize your curr variable.
From this :
let curr = new Date();
to this:
let curr = new Date(new Date().getTime() - (7 * 24 * 60 * 60 * 1000));
I use the getTime() method to get the epoch of today's date and subtract exactly the milliseconds passed in 7 days (or 1 week).
If I understand your question correctly, you must take into consideration when current day is sunday to get current week first day (monday).
let curr = new Date();
let week = [];
for (let i = 1; i <= 7; i++) {
let first = curr.getDate() - curr.getDay() + i;
if (curr.getDay() === 0){
first = curr.getDate() - 6;
}
let day = new Date(curr.setDate(first)).toISOString().slice(0, 10);
week.push(day);
};
console.log(week)
Start the for loop from 0
Like so
let curr = new Date();
let week = [];
for (let i = 0; i < 7; i++) {
let first = curr.getDate() - curr.getDay() + I;
let day = new Date(curr.setDate(first)).toISOString().slice(0, 10);
week.push(day);
};
console.log(week)
Remember, if you start from 1 and add 1 to the current date it will return tomorrow, and if you add 0 to today it retustns this date.
You can use moment.js library
let week = [];
let firstDayOfWeek = moment().startOf('week');
for (let i = 0; i < 7; i++) {
week.push(moment(firstDayOfWeek).add(i, 'd'));
};
console.log(week)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

Increase number twice a week

How would you increase a a number on a webpage twice a week on specific days and times?
For example the webpage would read:
"2 Apples"
However every Tuesday & Thursday at 9:00pm the number should increase by two.
So by Friday the number should have increased to 6 "Apples"
What's a simple way to increment this in Javascript, php or Jquery?
As it was mentionned in the comments, I advise you to use a cron to handle this.
First, you have to store your value somewhere (file, databse, ...). Then, you should create a cron job, that runs a code that increase and update your value at the given days of the week.
Some help about crons : https://en.wikipedia.org/wiki/Cron#Examples
I would add this post about cron and php : Executing a PHP script with a CRON Job
Hope it helps
Here a Javascript version, you can pass it the date it should start counting, the date you want to know the ammount of apples of, the days of the week apples will be added, the hours of the day the updat will take place and the ammount of apples that will be added on each of these dates.
Date.prototype.addDays = function (days) {
var result = new Date(this);
result.setDate(result.getDate() + days);
return result;
}
Date.prototype.addHours = function (hours) {
var result = new Date(this);
result.setHours(result.getHours() + hours);
return result;
}
function getApples(startdate, date, updateDays, updateTime, applesPerUpdate) {
var startDay = startdate.getDay();
var firstUpdateDate;
for(day of updateDays) {
if (day >= startDay) {//assumes startdate has no time added
firstUpdateDate = startdate.addDays(day - startDay).addHours(updateTime);
break;
}
}
if (!firstUpdateDate)
firstUpdateDate = startdate.addDays(7 - (startDay - updateDays[0])).addHours(updateTime);
var updateDaysReverse = updateDays.slice(0).reverse();//clones the array
var dateDay = date.getDay();
var lastUpdateDate;
for(day of updateDaysReverse) {
if (day < dateDay || day == dateDay && date.getHours() > updateTime) {
lastUpdateDate = date.addDays(day - dateDay);
break;
}
}
if (!lastUpdateDate)
lastUpdateDate = date.addDays(updateDaysReverse[0] - (7 + dateDay));
lastUpdateDate = new Date(Date.UTC(1900 + lastUpdateDate.getYear(), lastUpdateDate.getMonth(), lastUpdateDate.getDate(), updateTime, 0, 0, 0));
var secs = Math.trunc((lastUpdateDate - firstUpdateDate));
if (secs < 0) return 0;
var dayDiffs = [];
for(day of updateDays)
dayDiffs.push(day - updateDays[0]);
var weeks = Math.trunc(secs / 604800000);
var days = Math.trunc((secs % 604800000) / 86400000);
var apples = weeks * updateDays.length;
for(diff of dayDiffs)
{
if (diff <= days)
apples++;
else
break;
}
return apples * applesPerUpdate;
}
// important, day and month is zero-based
var startDate = new Date(Date.UTC(2016, 01, 07, 0, 0, 0, 0));
var updateDays = [2, 4];// 0 = sunday , have to be in order and must be 0 <= x < 7
var updateTime = 9;
console.log(getApples(startDate, new Date(), updateDays, updateTime, 2));
Was more coplicated than I thaught, and i havn't testet it much, so there may be bugs.
Here is a plunker to play with the values.

Find when month appears five times in JavaScript loop (date, string)

I am building a paycheck month calculator. If you normally get paid every other week, most months will have two paychecks but two months of each year will have three paychecks.
My program works as expected, it appends to a list the date of everyday starting today (today being a Friday). Now I would like to make list items with the same month that appears five times stand out, simple coloring would work.
Can this be done with a second function for li in ul and then if li[i] string[4][6] === the next li[i][4][6] and then somehow search for five? I'm not sure how the logic would work. The reason why I picked [4][6] is because in each list item, the months are all three letter abbreviations that occupy the same part of the string.
How can this be done?
var d;
var week = 7;
function getDates() {
for (var i = 0; i < 52; i++) {
d = new Date();
d.setDate(d.getDate() + week);
$('#date').append("<li>" + d + "</li>");
week += 7;
};
}
$(document).ready(function() {
getDates();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="date"></ul>
A dirty example:
var d;
var week = 7;
function getDates() {
for (var i = 0; i < 52; i++) {
d = new Date();
d.setDate(d.getDate() + week);
$('#date').append("<li data-mth='"+d.getMonth()+"'>" + d + "</li>");
week += 7;
}
$('li[data-mth]').each(function(){
var $group = $('li[data-mth="'+ $(this).data("mth") +'"]');
if( $group.length > 4 ) $group.addClass("standOut");
});
}
$(getDates);
.standOut{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="date"></ul>
You could put dates in a array where the month is the key, then loop the months and if the count on that month == 5 colour all the dates.
var d;
var week = 7;
$(document).ready(function() {
getDates();
});
function getDates() {
var months = new Array;
for (var i = 0; i < 52; i++) {
d = new Date();
d.setDate(d.getDate() + week);
var month = d.getMonth();
if(!months[month]) months[month] = new Array;
months[month].push(d);
week += 7;
};
plot_months(months);
}
function plot_months(months){
$.each(months,function(key,month){
var style = "";
if(month.length > 4) style = "color:red;";
$.each(month,function(week,date){
$('#date').append('<li style="'+style+'">' +date+ "</li>");
});
});
}`
See this fiddle

Why its not giving me the correct total month?

Why it's not giving me the correct total month? (with compared to current mm-yyyy)
function get_total_month(mm,yyyy) {
// custom inputs
var start_date = new Date(yyyy, mm, 01);
// current date
var today_date = new Date();
var today_year = today_date.getFullYear();
var today_month = today_date.getMonth();
var today_day = today_date.getDate();
var end_date = new Date(new Date(today_year, today_month, today_day));
// compare the given date with current date to find the total months
var total_months = (end_date.getFullYear() - start_date.getFullYear())*12 + (end_date.getMonth() - start_date.getMonth());
return total_months;
}
alert(
get_total_month(01, 2014)
);
Giving me: 20 instead of 22
That's because the Date.prototype.getMonth method returns a 0-11 number. So:
January = 0
February = 1
...
December = 11
I think this is what you are looking for, it is another version of your code. But I think is shorter and easier to understand. What do you think?
(I added the +2 to adjust the result to what you are expecting the function to return)
function monthDifference(startDate) {
var months;
var currentDate = new Date();
months = (currentDate.getFullYear() - startDate.getFullYear()) * 12;
months -= startDate.getMonth() + 1;
months += currentDate.getMonth();
return months <= 0 ? 0 : (months + 2);
}
alert(monthDifference(new Date(2014,0)) );
alert(monthDifference(new Date(2013,11)) );

total number of sundays in a month

I am using following code to determine total number of sundays in a month, however it gives incorrect result
function sundaysInMonth(start) {
var dat = new Date('1 ' + start);
var y = dat.getFullYear();
var m = dat.getMonth() + 1;
var days = new Date( y,m,0 ).getDate();
var sundays = [ 8 - (new Date( m + '/01/' + y ).getDay()) ];
for ( var i = sundays[0] + 7; i < days; i += 7 ) {
sundays.push( i );
}
return sundays.length;
}
When I call above functions like console.log(sundaysInMonth('September 2013')); then it returns 4 whereas September 2013 has 5 sundays.
I am getting above code from this post
Loops are not needed for this calculation.
function sundaysInMonth(start) {
var d = new Date('1 ' + start); // May not parse in all browsers
var ndays = new Date( d.getFullYear(), d.getMonth()+1, 0 ).getDate();
return Math.floor((ndays + (d.getDay() + 6) % 7) / 7);
}
Test for all months in 2013: http://jsfiddle.net/rGN28/2/
Aw, Matt beat me by one minute! I came up with basically the same solution, only with more comments. ;)
function sundaysInMonth(sMonthAndYear) {
// Get the year and month as integers
var dDate = new Date('1 ' + sMonthAndYear);
var y = dDate.getFullYear();
var m = dDate.getMonth() + 1;
// Get the number of days in the month
var iDayCount = new Date( y,m,0 ).getDate();
// Find the first Sunday
var iFirstSunday = (8 - dDate.getDay());
if (iFirstSunday > 7) {iFirstSunday = 1};
// Calculate the total number of Sundays in the month
var iSundayCount = Math.ceil ((iDayCount + 1 - iFirstSunday) / 7);
// Return the count
return iSundayCount;
}
Check this. I just fixed issue in your code
function sundaysInMonth(start) {
var dat = new Date('1 ' + start);
var y = dat.getFullYear();
var m = dat.getMonth() + 1;
var days = new Date( y,m,0 ).getDate();
var sundays = [ (8 - (new Date( m + '/01/' + y ).getDay())) % 7 ];
for ( var i = sundays[0] + 7; i < days; i += 7 ) {
sundays.push( i );
}
return sundays.length;
}
In array variable sundays we need to intially store the first day value which is a sunday. There was a small bug for months with Day 1 is sunday. For example as in your question September 2013
For these months your code will store 8 instead of 1 sundays array as first sunday. I fixed it
Although the question is old but here is my attempt to find number of Sundays in a month if anyone needs help.
<?php
$year = 2020; // Year to check
$month = 1; // Month to check (1-12)
// Get the first and last day of the month as timestamps
$firstDay = strtotime("{$year}-{$month}-01");
$lastDay = strtotime("+1 month", $firstDay);
// Initialize a counter variable
$numSundays = 0;
// Loop through each day of the month
for ($i = $firstDay; $i < $lastDay; $i = strtotime("+1 day", $i)) {
// Get the day of the week for the current day
$dayOfWeek = date("l", $i);
// If the day is Sunday, increment the counter
if ($dayOfWeek == "Sunday") {
$numSundays++;
}
}
// Print the number of Sundays
echo "Number of Sundays: $numSundays\n";
?>

Categories