How to iterate week number, start/end date of weeks using moment - javascript

How can I get all week number, from/to date of specific month?
The below code is what I construct to display week number, from/to date of specific month
and it returns infinite loop whenever I insert the function inside loop.
function getISOWeeksInMonth(month, year) {
let weekStart = new Date(year, month - 1, 1);
weekStart.setDate(weekStart.getDate() - (weekStart.getDay() || 7) + 1);
let weekEnd = new Date(weekStart);
weekEnd.setDate(weekEnd.getDate() + 6);
let weekNum = moment(weekStart, "YYYY-MM-DD").week()
let weeks = [];
do {
weeks.push({
weekNum : weekNum++,
start: new Date(weekStart),
end: new Date(weekEnd)
});
weekStart.setDate(weekStart.getDate() + 7);
weekEnd.setDate(weekEnd.getDate() + 7);
} while (weekStart.getMonth() < month);
return weeks;
}
_.forEach(moment.months(), function (month_name) {
var month_number = moment().month(month_name).format("MM");
getISOWeeksInMonth(month_number, 2022).forEach(week => console.log(
'Week : ' + week.weekNum +
'\nStart: ' + week.start.toDateString() +
'\nEnd : ' + week.end.toDateString())
);
})
Result should return the list the week number, from/to date
Sample Url:
https://savvytime.com/week-number/philippines/2022
Here is the sample when I run the function outside loop:
function getISOWeeksInMonth(month, year) {
let weekStart = new Date(year, month - 1, 1);
weekStart.setDate(weekStart.getDate() - (weekStart.getDay() || 7) + 1);
let weekEnd = new Date(weekStart);
weekEnd.setDate(weekEnd.getDate() + 6);
let weekNum = moment(weekStart, "YYYY-MM-DD").week()
let weeks = [];
do {
weeks.push({
weekNum : weekNum++,
start: new Date(weekStart),
end: new Date(weekEnd)
});
weekStart.setDate(weekStart.getDate() + 7);
weekEnd.setDate(weekEnd.getDate() + 7);
} while (weekStart.getMonth() < month);
return weeks;
}
getISOWeeksInMonth(1, 2022).forEach(week => console.log(
'Week : ' + week.weekNum +
'\nStart: ' + week.start.toDateString() +
'\nEnd : ' + week.end.toDateString())
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>

function getISOWeeksInMonth(month, year) {
let weekStart = new Date(year, month - 1, 1);
weekStart.setDate(weekStart.getDate() - (weekStart.getDay() || 7) + 1);
let weekEnd = new Date(weekStart);
weekEnd.setDate(weekEnd.getDate() + 6);
let weeks = [];
do {
let weekNum = moment(weekStart, "YYYY-MM-DD").week()
weeks.push({
weekNum : weekNum,
start: new Date(weekStart),
end: new Date(weekEnd)
});
weekStart.setDate(weekStart.getDate() + 7);
weekEnd.setDate(weekEnd.getDate() + 7);
} while (weekStart.getMonth() < month && (weekStart.getMonth() || (month < 12) ));
return weeks;
}
let _ = moment.months()
_.forEach(function (month_name) {
var month_number = moment().month(month_name).format("MM");
getISOWeeksInMonth(month_number, 2022).forEach(week => console.log(
'Week : ' + week.weekNum +
'\nStart: ' + week.start.toDateString() +
'\nEnd : ' + week.end.toDateString())
);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>
When you calculate the weeks in December (month 12), you're starting with the last week in the prior month (November, i.e. 11), and in your do {...} while loop, you're adding 7 days to weekStart. So far so good, but your while (weekStart.getMonth() < month) is checking the 0-11 value of weekStart.getMonth(), and when it rolls forward from 11, instead of going to 12 it goes to 0. So it is always less than 12 (December!)!
You can fix this by adjusting your while to:
while (weekStart.getMonth() < month && (weekStart.getMonth() || (month < 12) ))

Related

Why is condition not working when I select more than 10 days?

This is my code what i am trying is to make a datepicker to select number of days selected without Saturday and Friday it is working correctly but when I select more than one weekend (2 Friday or 2 sat) and the last day is weekend it escapes the last weekend like if day 30 is Saturday and i select from day 1 to day 30 it gives me 23 how ever if I select 1 to 28 it gives me 22.
var date = new Date();
var tomorrow = new Date();
tomorrow.setDate(date.getDate() + 1);
$('#picker').daterangepicker({
"linkedCalendars": true,
"showCustomRangeLabel": false,
"startDate": date.getDate(),
"endDate": tomorrow,
"cancelClass": "btn-danger",
"minDate": date.getDate(),
"opens": "center",
"autoApply": true
}, function(start, end) {
function parseDate(str) {
var mdy = str.split('-');
var x = new Date("'" + mdy[0] + "-" + mdy[1] + "-" + mdy[2]);
return x;
}
var between = [];
function datediff(first, second) {
var currentDate = new Date(first);
between = [];
while (currentDate <= second) {
between.push("'" + currentDate.getFullYear() + "-" + (currentDate.getMonth() + 1) + "-" + currentDate.getDate() + "'");
currentDate.setDate(currentDate.getDate() + 1);
}
//return Math.round((second-first)/(1000*60*60*24))+1;
}
datediff(parseDate(start.format('YYYY-MM-DD')), parseDate(end.format('YYYY-MM-DD')));
var s = "",
n = "",
fri = "",
sat = "",
i;
var number = between.length;
function getweekend() {
for (i = 0; i <= number + 1; i++) {
s = new Date(between[i]);
n = s.getDay();
fri = (n === 5);
sat = (n === 6);
if (fri) {
console.log("fri");
number = number - 1;
continue;
} else if (sat) {
console.log("sat");
number = number - 1;
continue;
} else {
console.log(n);
continue;
}
}
console.log("after minus:" + number);
}
console.log("plus minus:" + number);
getweekend();
});

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 })

Javascript increment and decrement YYYY-MM-DD by 1 day

I got this from another stack question
incr_date(date_str){
let parts = date_str.split("-");
let dt = new Date(
parseInt(parts[0], 10), // year
parseInt(parts[1], 10) - 1, // month (starts with 0)
parseInt(parts[2], 10) // date
);
dt.setDate(dt.getDate() + 1);
parts[0] = "" + dt.getFullYear();
parts[1] = "" + (dt.getMonth() + 1);
if (parts[1].length < 2) {
parts[1] = "0" + parts[1];
}
parts[2] = "" + dt.getDate();
if (parts[2].length < 2) {
parts[2] = "0" + parts[2];
}
return parts.join("-");
}
It works but how can I convert this function to decrement the date instead of increment?
I'm doing this on a react native component so I dont want to import any javascript libraries like moment.js
function dateAdd(dte){
var date = new Date(dte);
date.setDate(date.getDate() + 1);
console.log("add one day= "+date)
}
function datesub(dte){
var date = new Date(dte);
date.setDate(date.getDate() - 1);
console.log("minus one day = "+ date)
}
dateAdd("01-01-2017")
datesub("01-01-2017")
I'd convert the string to Javascript understandable format, increment a day and convert it back to user understandable format. I'm using the flag(Boolean) to determine weather to Increment the date and vice versa.
var convertDate = function(dt, flag) {
var dateArr = dt.split('-');
var tempDate = new Date();
var mm = dateArr[1] - 1; //Javascript considers 0 as Jan
tempDate.setFullYear(dateArr[0]);
tempDate.setMonth(mm);
tempDate.setDate(dateArr[2]);
if (flag) {
tempDate.setDate(tempDate.getDate(dateArr[2]) + 1);//Add's one day
} else {
tempDate.setDate(tempDate.getDate(dateArr[2]) - 1);//Sub's one day
}
var userFriendlyMonth = (Number(tempDate.getMonth()) + 1); //user considers 1 as Jan
return tempDate.getFullYear() + '-' + userFriendlyMonth + '-' + tempDate.getDate();
}
document.getElementById("increment").innerHTML = convertDate('2018-11-30', true);
document.getElementById("decrement").innerHTML = convertDate('2018-11-30', false);
<div>Increment: <span id="increment"></span></div>
<div>Decrement: <span id="decrement"></span></div>

Date format change

I would like to change the date format in my code like that - > 19.7.2016
Could anyone help me, please?
function calcWorkingDays(fromDate, days) {
var count = 0;
var m = new Date();
while (count < days) {
fromDate.setDate(fromDate.getDate() + 1);
if (fromDate.getDay() != 0 && fromDate.getDay() != 6) // Skip weekends
count++;
}
return fromDate;
}
alert(calcWorkingDays(new Date(), 4));
You need to format the dateobject to your likeness:
Extract the Day, Month and Year from your DateObject:
var month = fromDate.getUTCMonth() + 1; //months from 1-12
//January=0, February=1, etc
var day = fromDate.getUTCDate();
var year = fromDate.getUTCFullYear();
newdate = day + "." + month + "." + year;
Complete Example:
function calcWorkingDays(fromDate, days) {
var count = 0;
var m = new Date();
while (count < days) {
fromDate.setDate(fromDate.getDate() + 1);
if (fromDate.getDay() != 0 && fromDate.getDay() != 6) // Skip weekends
count++;
}
var month = fromDate.getUTCMonth() + 1;
var day = fromDate.getUTCDate();
var year = fromDate.getUTCFullYear();
newdate = day + "." + month + "." + year;
return newdate;
}
alert(calcWorkingDays(new Date(), 4));
Other possible examples are:
new Date().toISOString()
"2016-02-18T23:59:48.039Z"
new Date().toISOString().split('T')[0];
"2016-02-18"
new Date().toISOString().replace('-', '/').split('T')[0].replace('-', '/');
"2016/02/18"
new Date().toLocaleString().split(',')[0]
"2/18/2016"
source
You should convert date to string:
function calcWorkingDays(fromDate, days) {
var count = 0;
var m = new Date();
while (count < days) {
fromDate.setDate(fromDate.getDate() + 1);
if (fromDate.getDay() != 0 && fromDate.getDay() != 6) // Skip weekends
count++;
}
return fromDate.getDate() + "." + (fromDate.getMonth()+1) + "." + fromDate.getFullYear();
}
alert(calcWorkingDays(new Date(), 4));

Amending the function to calculate into the new year and not return the value 12/33/2014

I need your help.
It seems that the function this_week('end') is returning a bad date of 12/33/2014 (mm/dd/yyyy) where it should properly read:
01/02/2015
function this_week(x) {
var today, todayNumber, fridayNumber, sundayNumber, monday, friday;
today = new Date();
todayNumber = today.getDay();
mondayNumber = 1 - todayNumber;
fridayNumber = 5 - todayNumber;
if (x === 'start') {
//var start_dd = today.getDate() + mondayNumber
var start_dd = today.getDate()
var start_mm = today.getMonth() + 1
var start_yyyy = today.getFullYear()
return start_mm + '/' + start_dd + '/' + start_yyyy
}
if (x === 'end') {
var end_dd = today.getDate() + fridayNumber
var end_mm = today.getMonth() + 1
var end_yyyy = today.getFullYear()
return end_mm + '/' + end_dd + '/' + end_yyyy
}
}
What needs to be done?
You have to use Date objects when increasing or decreasing the date..
function this_week(x) {
var date, todayNumber, fridayNumber;
date = new Date();
todayNumber = date .getDay();
mondayNumber = 1 - todayNumber;
fridayNumber = 5 - todayNumber;
if (x === 'start') {
date.setDate(date.getDate()+ mondayNumber);
}
else if (x === 'end') {
date.setDate(date.getDate()+ fridayNumber);
}
var end_dd = date.getDate().toString();
end_dd = (end_dd.length == 2)?end_dd:"0"+end_dd;
var end_mm = (date.getMonth() + 1).toString();
end_mm = (end_mm.length == 2)?end_mm:"0"+end_mm;
var end_yyyy = date.getFullYear().toString();
return end_mm + '/' + end_dd + '/' + end_yyyy;
}
document.write(this_week('end'));
Note that the month code for January is 0
For a much simpler version:
function this_week(x,d) {
var d = d || new Date(),
offset = 0;
switch (x){
case 'start':
offset = 1 - d.getDay();
break;
case 'end':
offset = 5 - d.getDay();
break;
}
d.setDate(d.getDate() + offset);
return d;
}
var oE = document.getElementById('o'),
tE = document.getElementById('t');
function $log(t){ oE.innerHTML += (t || '') + "\r\n"; }
function $fmt(d){ return [d.getMonth() + 1, d.getDate(), d.getFullYear() ].map(function(v){ return v < 10 ? '0' + v : v; }).join('/'); }
function c(el){ try { var d = new Date(el.value); tE.innerHTML = 'Start: ' + $fmt(this_week('start',d)) + '; End: ' + $fmt(this_week('end',d)); } catch (e) { tE.innerHTML = 'Invalid Date'; } }
$log( 'Fixed dates' );
var ds = [
new Date(2014, 12 - 1, 29),
new Date(2015, 1 - 1, 1)
];
for (var i = 0; i < ds.length; i++){
$log( $fmt(ds[i]) + ' start » ' + $fmt(this_week('start', ds[i])) );
$log( $fmt(ds[i]) + ' end » ' + $fmt(this_week('end', ds[i])) );
}
$log();
$log( 'Based on today:' );
$log( $fmt(this_week('start')) );
$log( $fmt(this_week('end')) );
$log();
$log('::All dates in mm/dd/yyyy format::');
<pre id="o"></pre>
<hr />
<input type="text" onchange="c(this);" placeholder="try me"><button>Try</button><span id="t"></span>
Assuming that a complete week may start on sunday or on monday, this function covers both:
function this_week(start, givendate, weekStartsOnsunday) {
givendate = givendate && givendate instanceof Date ? givendate : new Date;
var today = givendate.getDay(),
isSunday = !weekStartsOnsunday && today < 1,
diff = !start
? (isSunday ? -2 : (5 - today))
: (isSunday ? -6 : (1 - today));
// set date to begin/end of week and return it formatted
return (givendate.setDate(givendate.getDate() + diff), format(givendate));
}
// format mm/dd/yyyy with leading zero's using an Array and Array.map
function format(date) {
return [ date.getDate(),
date.getMonth()+1,
date.getFullYear()
].map(function (v) {return v <10 ? '0'+v : v;})
.join('/');
}
var log = Helpers.log2Screen;
// today and week starts on monday
log('`this_week()`: ', this_week());
log('`this_week(true)`: ',this_week(true));
// given date is sunday, week starts on monday
log('`this_week(false, new Date(\'2015/01/04\'))`: ',
this_week(false, new Date('2015/01/04')), ' (week ends on sunday)');
log('`this_week(true, new Date(\'2015/01/04\'))`: ',
this_week(true, new Date('2015/01/04')), ' (week ends on sunday)');
// given date is sunday, week starts on sunday
log('`this_week(false, new Date(\'2015/01/04\'), true)`: ',
this_week(false, new Date('2015/01/04'), true), ' (week starts on sunday)')
log('`this_week(true, new Date(\'2015/01/04\'), true)`: ',
this_week(true, new Date('2015/01/04'), true), ' (week starts on sunday)');
<script src="http://kooiinc.github.io/JSHelpers/Helpers-min.js"></script>

Categories