Add future days to Javascript excluding on sunday - javascript

I have the following javascript code that allows a user to only select four days in future from today's date.
$(function() {
var dtToday = new Date();
var month = dtToday.getMonth() + 1;
if (dtToday.getDay() === 0) {
var day = dtToday.getDate() + 5;
} else {
var day = dtToday.getDate() + 4;
}
var year = dtToday.getFullYear();
if (month < 10)
month = '0' + month.toString();
if (day < 10)
day = '0' + day.toString();
var maxDate = year + '-' + month + '-' + day;
$('.datepicker').attr('max', maxDate);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I would like the code to skip Sunday while incrementing the future days by four. I have tried using if statements but they only check if today's date is sunday while i would like to achieve a situation whereby if any of the future 4 days is Sunday, it should skip it.
Thanks

If today is Wednesday (3), Thursday (4), Friday (5), or Saturday (6), then your 4-day window would include Sunday (hence you should add 1 to days).
So do this:
var day = dtToday.getDate() + 4;
if(dtToday.getDay() > 2) {
day += 1;
}
So your script would be:
$(function(){
var dtToday = new Date();
var month = dtToday.getMonth() + 1;
var day = dtToday.getDate() + 4;
if(dtToday.getDay() > 2) {
day += 1;
}
var year = dtToday.getFullYear();
if(month < 10)
month = '0' + month.toString();
if(day < 10)
day = '0' + day.toString();
var maxDate = year + '-' + month + '-' + day;
$('.datepicker').attr('max', maxDate);
});

Related

Limit a date in input type date

I would like to limit the date so that the user does not have to select a date of less than one year, but I wish that it is done automatically compared to the date of the system. If anyone has ideas I'm grateful.
You can get the current date and subtract an year from the current year and set min attribute
var dtToday = new Date();
var month = dtToday.getMonth() + 1;
var day = dtToday.getDate();
var year = dtToday.getFullYear();
if(month < 10)
month = '0' + month.toString();
if(day < 10)
day = '0' + day.toString();
var minDate = (year-1) + '-' + month + '-' + day;
document.getElementById('dt').setAttribute('min', minDate);
<input type="date" id="dt">
You can specify the min and max property for the input element:
let input = document.querySelector("#test");
let nextYear = new Date(new Date().setFullYear(new Date().getFullYear() + 1));
let today = new Date();
input.max = formatDate(nextYear)
input.min = formatDate(today)
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
<input type="date" id="test"/>

Get all mondays in the year

I always have problems figuring out dates functions
var d = new Date(),
month = d.getMonth(),
mondays = [];
d.setDate(1);
// Get the first Monday in the month
while (d.getDay() !== 1) {
d.setDate(d.getDate() + 1);
}
// Get all the other Mondays in the month
while (d.getMonth() === month) {
var pushDate = new Date(d.getTime());
mondays.push(pushDate.getDate() + '-' + (pushDate.getMonth()+1) + '-' + pushDate.getFullYear());
d.setDate(d.getDate() + 7);
}
I am using this function to get all mondays in a month, current month.
How can I adapt this code to get all remaining mondays in the year?
Just loop through the year instead of the month. The code is the same as yours, it works fine. just changed month -> year and getMonth() -> getYear()
var d = new Date(),
year = d.getYear(),
mondays = [];
d.setDate(1);
// Get the first Monday in the month
while (d.getDay() !== 1) {
d.setDate(d.getDate() + 1);
}
// Get all the other Mondays in the month
while (d.getYear() === year) {
var pushDate = new Date(d.getTime());
mondays.push(pushDate.getDate() + '-' + (pushDate.getMonth()+1) + '-' + pushDate.getFullYear());
d.setDate(d.getDate() + 7);
}
var x = new Date();
//set the financial year starting date
x.setFullYear(2016, 03, 01);
//set the next financial year starting date
var y = new Date();
y.setFullYear(2017, 03, 01);
var j = 1;
var count = 0;
//getting the all mondays in a financial year
for (var i = 0; x < y; i += j) {
if (x.getDay() === 1) {
document.write("Date : " + x.getDate() + "/" +
(x.getMonth() + 1) + "<br>");
x = new Date(x.getTime() + (7 * 24 * 60 * 60 * 1000));
j = 7;
count++;
} else {
j = 1;
x = new Date(x.getTime() + (24 * 60 * 60 * 1000));
}
}
document.write("total mondays : " + count + "<br>");
This is just an alternative, it uses a simpler method of getting the first day of the month.
// Get all Mondays in year from provided date
// Default today's date
function getMondays(d) {
// Copy d if provided
d = d ? new Date(+d) : new Date();
// Set to start of month
d.setDate(1);
// Store end year and month
var endYear = d.getFullYear() + 1;
var endMonth = d.getMonth();
// Set to first Monday
d.setDate(d.getDate() + (8 - (d.getDay() || 7)) % 7);
var mondays = [new Date(+d)];
// Create Dates for all Mondays up to end year and month
while (d.getFullYear() < endYear || d.getMonth() != endMonth) {
mondays.push(new Date(d.setDate(d.getDate() + 7)));
}
return mondays;
}
// Get all Mondays and display result
// SO console doensn't show all results
var mondays = getMondays();
mondays.forEach(function(mon) {
console.log(mon.toLocaleString(void 0, {
weekday: 'short',
day: 'numeric',
month: 'short',
year: 'numeric'
}));
});
// Count of Mondays, not all shown in SO console
console.log('There are ' + mondays.length + ' Mondays, the first is ' + mondays[0].toString())
With date-fns
https://date-fns.org/v2.28.0/docs/eachWeekOfInterval
eachWeekOfInterval({
start: new Date('2022/01/01'),
end: new Date('2022/5/31')
}, { weekStartsOn: 1 })

Change date range in javascript

I am trying to set start and end date in date picker where start date is week before current date and end date is week after start date. In certain condition it gives me 0 for start date. Can anyone look into code below and help me to get proper date range when current date is first day of the month or last date of the month. Thanks for your help.
var date = new Date();
//When current date was less then 7 in some situation it giving me error. So, I am checking current date and randomly subtract 3.
//if current date is less then 7 then get the last day of the previous month
if (date.getDate() <= 7) {
day = new Date(date.getFullYear(), date.getMonth(), 0);
startdate = day.getDate() - 3;
month = day.getMonth() + 1;
year = day.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = day;
console.log("App Config: lasy day: " + startdate + "\nmonth: " + month + "\nyear:" + year);
}
else {
startdate = date.getDate() - 7;
month = date.getMonth() + 1;
year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = day;
console.log("App Config: day: " + startdate + "\nmonth: " + month + "\nyear:" + year);
}
return month + "/" + startdate + "/" + year;
Have you tried this:
var dt = new Date();
var weekBefore = dt.setDate(dt.getDate() - 7);
var weekAfter = dt.setDate(dt.getDate() + 7);
JavaScript will figure it out automatically the date 7 days before and after!
If you are ok with plugins I would suggest Moment.js which is great for date handling. Adding a week would be as easy as
var inOneWeek = moment().add(1, 'weeks');//.format('DD/MM/YYYY'); if u want it in DD/MM/YYYY format
var oneWeekAgo = moment().add(-1, 'weeks');//.format('DD/MM/YYYY');
otherwise #sabotero's answer would do as well.

append 0 infront of single digits

Hi i'm trying to add a 0 infront of days / months with single digits. I tried using regular expressions but it doesn't seem to work. is there something i'm missing?
var newDate = new Date();
alert(newDate);
newDate.setDate(newDate.getDate() + 1);
alert(newDate);
var year = newDate.getFullYear();
alert(year);
var month = (newDate.getMonth()+1).replace(/\b(\d{1})\b/g, '0$1');
alert(month);
var day = newDate.getDate().replace(/\b(\d{1})\b/g, '0$1');
alert(day);
I'd better use these constructions.
var month = (newDate.getMonth()+1).toString();
month = month.length < 2 ? '0' + month : month;
alert(month);
var day = (newDate.getDate()+1).toString();
day = day.length < 2 ? '0' + day : day;
alert(day);
You're running replace on a Number here.
var month = (newDate.getMonth()+1).replace(/\b(\d{1})\b/g, '0$1');
// ...
var day = newDate.getDate().replace(/\b(\d{1})\b/g, '0$1');
You need to convert it to a String before running replace.
var month = (newDate.getMonth()+1).toString().replace(/\b(\d{1})\b/g, '0$1');
var day = newDate.getDate().toString().replace(/\b(\d{1})\b/g, '0$1');
How about this:
var month = "" + (newDate.getMonth()+1);
if (month.length==1) month = "0" + month;
alert(month);
var day = "" + newDate.getDate();
if (day.length == 1) day = "0" + day;
alert(day);

Get date for every Thursday in the year Javascript

Given a day of the week (var day) the code below will print the date of each
day in the year starting from today. Since 4 = Thursday, I will get a list
of all the Thursdays left in the year. I was just curious if there was some
'neater' way to accomplish this?
var day = 4;
var date = new Date();
var nextYear = date.getFullYear() + 1;
while(date.getDay() != day)
{
date.setDate(date.getDate() + 1)
}
while(date.getFullYear() < nextYear)
{
var yyyy = date.getFullYear();
var mm = (date.getMonth() + 1);
mm = (mm < 10) ? '0' + mm : mm;
var dd = date.getDate();
dd = (dd < 10) ? '0' + dd : dd;
console.log(yyyy + '-' + mm + '-' + dd)
date.setDate(date.getDate() + 7);
}
Output:
2011-02-10
2011-02-17
2011-02-24
2011-03-03
2011-03-10
..etc
Well, it would look a lot prettier if you used Datejs.
var thursday = Date.today().next().thursday(),
nextYear = Date.next().january().set({day: 1}),
format = 'yyyy-MM-dd';
while (thursday.isBefore(nextYear))
{
console.log(thursday.toString(format));
thursday = thursday.add(7).days();
}
See also http://code.google.com/p/datejs/.

Categories