I am populating all the months in Dropdown list, and i am enabling up to current month and remain months will be disabled, like
var date = new Date();
var month = new Date().getMonth() + 1;
var weeknum=//getting week number of the month
var options = $('#ddlMonth option');
var values = $.map(options, function (option) {
return option.value;
});
for (var i = 0; i <= values.length; i++) {
if (i > month) {
$("#ddlMonth option[value=" + i + "]").attr('disabled', true);
}
}
$('#ddlMonth').val(month);
Now I want to disable month if current week of the current month is first week.
Date.prototype.getMonthWeek = function(){
var firstDay = new Date(this.getFullYear(), this.getMonth(), 1).getDay();
return Math.ceil((this.getDate() + firstDay)/7);
}
Demo
http://jsfiddle.net/ay10bmpm/
Ref
http://www.somethinghitme.com/2010/04/14/how-to-get-the-week-in-a-month-for-a-date-with-javascript/
function(){
var d = new Date();
d.setHours(0,0,0);
d.setDate(d.getDate()+4-(d.getDay()||7));
return Math.ceil((((d-new Date(d.getFullYear(),0,1))/8.64e7)+1)/7);
};
This will get you the week in year and from this is simple math. (maybe not so simple for 5 weeks per month).
Or you can get the number of the week function from this fiddle : http://jsfiddle.net/OlsonDev/5mXF6/1/ (works with 5 weeks, tested)
Related
I have a problem with creating a calendar in JavaScript. I want to display dates from Monday to Sunday. So this is my DateSet function:
dateSets(year) {
const today = new Date();
year = today.getFullYear();
let firstDayOfWeek = this.getDateOfWeek(this.currentWeekNumber, year);
let dates = [];
for (let i = 0; i < 7; i++) {
dates.push(
new Date(firstDayOfWeek.setDate(firstDayOfWeek.getDate() + i))
);
}
return dates;
}
getDateOfWeek(this.currentWeekNumber, year) gets the Monday of the week. But with this code displays 9/8/2021 10/8/2021 12/8/2021 15/8/2021 19/8/2021 24/8/2021 30/8/2021.
So when I change the i in the for with 1 it displays like this but I cannot use this because I cannot get Monday: 10/8/2021 11/8/2021 12/8/2021 13/8/2021 14/8/2021 15/8/2021 16/8/2021.
I want to build a simple function that would receive a particular month to check. In return it would provide the amount of weekend days it counted within that month.
In the code I'm assuming that the current year is the relevant year to simplify the task.
The problem is it's not return the proper answer for weekends in reality when going over a calendar and counting it manually.
workDays(4); // submitting the month to check for
function workDays(monthCheck) //Calculate the actual work days: eliminate weekends from month
{
// init month to check as proper date variable and setting days to 0 for total days
var month = new Date(new Date().getFullYear(), monthCheck+1, 0);
var daysOff = 0; //init
for(i = month.getDate(); i>=0; i--) //check for days that = 0 or 6 (Sunday OR Saturday)
{
if(new Date(month.getFullYear(), monthCheck, i).getDay() == 0 || new Date(month.getFullYear(), monthCheck, i).getDay() == 6)
{
console.log(daysOff++); // weekend day added to weekend days counter
}
}
return console.log("The days off for the month of " + (month.getMonth()) + " are " + daysOff + " days off.");
}
I find your logic very confusing. I refactored the code to an (imo) more readable version, and the result seems as expected:
nonWorkDays(4);
function nonWorkDays(month)
{
var current = new Date(new Date().getFullYear(), month - 1, 1);
var daysOff = 0; //init
// as long as our date is in the requested month
while (current.getMonth() == month -1) {
// saturday or sunday?
if (current.getDay() == 0 || current.getDay() == 6) {
daysOff++;
console.log(daysOff, current);
}
// move to next day
current.setDate(current.getDate() + 1);
}
console.log("The days off for the month of " + month + " are " + daysOff + " days off.");
return daysOff;
}
And a fiddle to demonstrate: https://jsfiddle.net/4kmtemfy/
Not sure where you went wrong but this seems right:
var d = new Date();
var getTot = daysInMonth(d.getMonth(),d.getFullYear());
var weekends = new Array();
for(var i=1;i<=getTot;i++){
var newDate = new Date(d.getFullYear(),d.getMonth(),i)
if(newDate.getDay()==0 || newDate.getDay()==6){
weekends.push(i)
}
}
console.log(weekends.length);
function daysInMonth(month,year) {
return new Date(year, month, 0).getDate();
}
Your issue is with monthCheck+1. Since months are zero indexed and you want the month number of the following month, don't subtract 1. You can also simplify the logic somewhat:
function workDays(monthCheck) {
// Create date for last day of month to check
var month = new Date(new Date().getFullYear(), monthCheck, 0);
var daysOff = 0;
// For each day of the month
for(var i = month.getDate(); i>=0; i--) {
// Add day off for Saturday and Sunday
if (!(month.getDay()%6)) {
daysOff++;
}
month.setDate(month.getDate()-1);
}
return daysOff;
}
var month = 4;
console.log('Days off for ' + month + ' are ' + workDays(month) + '.');
In a form, I define a start date, an end date, and weekdays
Example:
Start date: 2017-02-07
End date: 2017-03-07
Weekdays: Monday and Thursday
Now I want to get all Mondays and Thursdays between start date and end date by using Javascript or jQuery.
Who can help me?
Thanks...
Simple code. Codepen
var startDate = new Date('2017-02-07');
var endDate = new Date('2017-02-17');
var monday = [];
var thursday = [];
for (var d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
if(d.getDay()==1)
monday.push(d);
else if(d.getDay()==4)
thursday.push(d);
}
You can parse date and iterate over increment 1 day and getDay to map with sun(0) to sat(6)
var startDate = new Date("2017-02-07");
var endDate = new Date("2017-03-07");
var totalMon = [];
var totalThu = [];
for (var i = startDate; i <= endDate; ){
if (i.getDay() == 1){
totalMon.push(i.getFullYear() + "-" + (i.getMonth()+1) + "-" + i.getDate());
}
if (i.getDay() == 4){
totalThu.push(i.getFullYear() + "-" + (i.getMonth()+1) + "-" + i.getDate());
}
i.setTime(i.getTime() + 1000*60*60*24);
}
console.log(totalMon.length ,totalMon);
console.log(totalThu.length ,totalThu);
Below code finds number of Mondays. You can modify it to calculate any day. It basically finds the difference of days in two dates. Divide it by 7 (this is the number of times everyday will come). Now for pending days loop through the dates and check if a desired day comes in this loop.
var startDate = new Date(2017, 02, 07);
var endDate = new Date(2017, 03, 07);
var dayDiff = Math.round((endDate-startDate)/(1000*60*60*24));
var numberOfMondays = Math.floor(dayDiff/7);
var remainingDays = dayDiff%7;
for(i=0;i<remainingDays;i++)
{
var dateObj = new Date();
dateObj.setDate(endDate.getDate() - i);
if(dateObj.getDay() == 2)
numberOfMondays=numberOfMondays+1;
}
alert(numberOfMondays);
PS : the other two answer are looping through all the dates. I will not suggest this. In code above the number of iterations in loop will never exceed 6 irrespective of the difference in dates.
I have to pretty much validate and check if the user is underage in ASP. So anyone under the age of 01/07/1998 is underage. I have 3 dropdown lists to select date, month and year. Im using JS. I try using concat and split but they dont work. Can anyone help with this?
function ValidateDate() {
var dDay = document.getElementById('DateList');
var dMonth = document.getElementById('MonthList');
var dYear = document.getElementById('YearList');
var day = dDay.selectedIndex;
var month = dMonth.selectedIndex;
var year = dYear.selectedIndex;
var firstValue = year + month + day;
var setyear = "1998";
var setmonth = "06";
var setdate = "01";
var secondValue = setyear + setmonth + setdate;
var firstDate = new Date();
firstDate.setFullYear(firstValue[0], (firstValue[1] - 1), firstValue[2]);
var secondDate = new Date();
secondDate.setFullYear(secondValue[0], (secondValue[1] - 1), secondValue[2]);
if (firstDate > secondDate) {
alert("Pass");
}
else {
alert("Fail");
}
}
<asp:CustomValidator ID="CustomValidatorDate" runat="server"
ErrorMessage=" You are underage" CssClass="error" Display="Dynamic" ClientValidationFunction="ValidateDate" ></asp:CustomValidator>
First of all your day, month and year variables are reading the index of the drop-downs and not their values.
For instance, you need to use:
var day = dDay.value,
month = dMonth.value,
year = dYear.value;
And then create date object as
var firstDate = new Date(year, month, day);
-Dipen
Is there any javascript function which takes one input parameter (e.g 04/2014 ) and return
12 months and dates with the same format
(e.g 04/2013.........................................04/2014)
i have this one
function calcFullMonth(startDate) {
//copy the date
var dt = new Date(startDate);
dt.setMonth(dt.getMonth() - 1);
return dt;
}
The logic that i have is this .But it gives me only one month back
I need to get 12 months and 1 year back and display them as you see second e.g.
Thanks
Just call your original function as many times as you need, and store them in an array.
function calcFullMonth(startDate, num) {
var months = [];
for (var i = 0; i < num; i++) {
var dt = new Date(startDate);
dt.setMonth(dt.getMonth() + i);
months[i] = dt;
}
return months;
}
For example, to get the current month until this month next year, use num = 13
console.log(calcFullMonth(new Date(), 13));
fiddle
Try the following function
function Get12MonthBack(input) {
var year = input.split("/")[1];
var month = input.split("/")[0];
var d = new Date(year, month);
d.setMonth(d.getMonth()-12);
return (d.getMonth().toString().length == 1 ? "0" + d.getMonth() : d.getMonth()) + "/" + d.getFullYear();
}
Tests
Get12MonthBack("03/2011")
"03/2010"
Get12MonthBack("11/2012")
"11/2012"