get last 14 Dates - javascript

Hey i want to get the last 14 days in JavaScript.
I tried following code:
var ourDate = new Date();
for (let index = 0; index < 14; index++) {
var pastDate = ourDate.getDate() - index;
ourDate.setDate(pastDate);
console.log(ourDate.toDateString(), " - ", index);
}
but the console output is following:
Sat Jan 23 2021 - 0
Fri Jan 22 2021 - 1
Wed Jan 20 2021 - 2
Sun Jan 17 2021 - 3
Wed Jan 13 2021 - 4
Fri Jan 08 2021 - 5
Sat Jan 02 2021 - 6
Sat Dec 26 2020 - 7
Fri Dec 18 2020 - 8
Wed Dec 09 2020 - 9
Sun Nov 29 2020 - 10
Wed Nov 18 2020 - 11
Fri Nov 06 2020 - 12
Sat Oct 24 2020 - 13
Which does not make sense.
Could someone help me with this?
I used this code: LINK TO TUTORIAL

I just solved it myself.
I never retested the ourDate so it first removed 0 than 1 than 2 but never reseted.
Just have to create the ourDate in the for loop:
for (let index = 0; index < 14; index++) {
var ourDate = new Date();
var pastDate = ourDate.getDate() - index;
ourDate.setDate(pastDate);
console.log(ourDate.toDateString(), " - ", index);
}

You can try this snippet:
const now = new Date();
const days = Array.from({ length: 14 }, (_, x) => new Date(now - 1000 * 60 * 60 * 24 * x));
for (let day of days) console.log(day.toDateString());
Or a more general solution:
const msInDay = 1000 * 60 * 60 * 24;
const daysAgo = (date, count) => new Date(date - msInDay * count);
const lastDays = (date, count) => Array.from({ length: count }, (_, x) => daysAgo(date, x));
const last14days = lastDays(new Date(), 14);
for (let day of last14days) console.log(day.toDateString());

Related

what is difference between these "new Date()"s?

var today = new Date();
var endYear = new Date(1995, 11, 31, 23, 59, 59, 999); // Set day and month
endYear.setFullYear(today.getFullYear()); // Set year to this year
console.log("Version 1: end year full date is ", endYear);
var msPerDay = 24 * 60 * 60 * 1000; // Number of milliseconds per day
var daysLeft = (endYear.getTime() - today.getTime()) / msPerDay;
var daysLeft = Math.round(daysLeft); //returns days left in the year
console.log(daysLeft,endYear);
// when l write that code answer is 245.
var today = new Date();
var endYear = new Date(2021, 0, 0, 0, 0, 0, 0); // Set day and month
console.log("Version 2: end year full date is ", endYear);
var msPerDay = 24 * 60 * 60 * 1000; // Number of milliseconds per day
var daysLeft = (endYear.getTime() - today.getTime()) / msPerDay;
var daysLeft = Math.round(daysLeft); //returns days left in the year
console.log(daysLeft,endYear);
// but when l add only 1 ms then answer returns like 244. but how is it possible? where has 1 day gone?
That is the difference with the time you set.
To be clear,
first endYear will print Thu Dec 31 2020 23:59:59
second endYear will print Thu Dec 31 2020 00:00:00
That is the difference you see there.
I will post the complete out put I received on console here as well.
Thu Dec 31 2020 23:59:59 GMT+0530 (India Standard Time)
245.0131708912037
245
Thu Dec 31 2020 00:00:00 GMT+0530 (India Standard Time)
244.01317090277777
244
==================EDIT==================
new Date(2021, 0, 0, 0, 0, 0, 0) calculates this to Dec 31st because date is indexed from 1 and not zero. If that value is zero it computes it as the day before the 31st of December.
For example,
new Date(Date.UTC(2021, 1, 0, 0, 0, 0, 0)) will print out Sat Jan 31 2021 05:30:00 GMT+0530 (India Standard Time)
and
new Date(Date.UTC(2021, 1, -1, 0, 0, 0, 0)) will print out Sat Jan 30 2021 05:30:00 GMT+0530 (India Standard Time)

Strange behavior when using Date.setDate() incremental by day

I am working on a functionality where I'd like to iterate particular dates between Date_A and Date_B.
Problem is when 'DateB' is in next month so the iterating process is overlapping to next month. Please see a line 12 of output. It seems like it starts incrementing months instead of days... Any suggestions, please? :)
iter: 0 , inspectedDate: Mon Apr 22 2019 00:00:00 GMT+0000 (UTC)
iter: 1 , inspectedDate: Tue Apr 23 2019 00:00:00 GMT+0000 (UTC)
iter: 2 , inspectedDate: Wed Apr 24 2019 00:00:00 GMT+0000 (UTC)
iter: 3 , inspectedDate: Thu Apr 25 2019 00:00:00 GMT+0000 (UTC)
iter: 4 , inspectedDate: Fri Apr 26 2019 00:00:00 GMT+0000 (UTC)
iter: 5 , inspectedDate: Sat Apr 27 2019 00:00:00 GMT+0000 (UTC)
iter: 6 , inspectedDate: Sun Apr 28 2019 00:00:00 GMT+0000 (UTC)
iter: 7 , inspectedDate: Mon Apr 29 2019 00:00:00 GMT+0000 (UTC)
iter: 8 , inspectedDate: Tue Apr 30 2019 00:00:00 GMT+0000 (UTC)
iter: 9 , inspectedDate: Wed May 01 2019 00:00:00 GMT+0000 (UTC)
iter: 10 , inspectedDate: Sat Jun 01 2019 00:00:00 GMT+0000 (UTC)
iter: 11 , inspectedDate: Wed Jul 03 2019 00:00:00 GMT+0000 (UTC)
iter: 12 , inspectedDate: Sat Aug 03 2019 00:00:00 GMT+0000 (UTC)
iter: 13 , inspectedDate: Wed Sep 04 2019 00:00:00 GMT+0000 (UTC)
example here: https://repl.it/repls/QuerulousSelfreliantDatabase
const inspectedDate = new Date('2019-04-22');
const today = new Date('2019-04-22');
let intervalCorrection = 0;
for (let dayOffset = 0; dayOffset < requestInterval; dayOffset++) {
inspectedDate.setDate(today.getDate() + dayOffset);
console.log('iter: ' + dayOffset, ', inspectedDate: ' + inspectedDate);
}
Try 'reseting' inspectedDate every iteration. Worked fine for me.
Changes I made to your code snippet:
const requestInterval = 14;
let today = new Date('2019-04-22').getDate();
let intervalCorrection = 0;
for (let dayOffset = 0; dayOffset < requestInterval; dayOffset++) {
const inspectedDate = new Date('2019-04-22');
inspectedDate.setDate(today + dayOffset);
console.log('iter: ' + dayOffset, ', inspectedDate: ' + inspectedDate);
}
The problem is that when you setDate and it's more than the current month's days that changes the month. Adding a bigger number again changes the mongth again:
const date = new Date("2019-02-01");
let day = 31;
let offset = 1;
date.setDate(day + offset); //goes to March
offset++;
console.log(date.toString());
date.setDate(day + offset); //goes to April
offset++;
console.log(date.toString());
Since you add a constant 22 (the value of today.getDate()) each time, you very quickly get to 30 and above which will start rolling over each month.
If you just want each consecutive day, then you don't need to have two dates and do a lot of calculations - just use a single date and increment the day by 1 each time - this will give you each day:
const inspectedDate = new Date('2019-04-22');
const requestInterval = 14;
for (let i = 0; i < requestInterval; i++) {
inspectedDate.setDate(inspectedDate.getDate() + 1); //advance one day
console.log('iter: ' + i, ', inspectedDate: ' + inspectedDate);
}
The problem here lies in that you are storing the date variable in a constant and altering its date using setDate only. This results in its moth getting changed which you are not handling.
On iter 9, it sets the date to 22 + 9, i.e, 31. But the month is 4(Apr) which is a 30 day month. So the date changes to Wed May 01 2019 00:00:00 GMT+0000 (UTC)
On iter 10, it sets the date to 22 + 10, i.e, 32. But the month is now 5(May) which is a 31 day month. So the date changes to Sat Jun 01 2019 00:00:00 GMT+0000 (UTC)
On iter 11, it sets the date to 33. The month is 6(Jun). So the date changes to Wed Jul 03 2019 00:00:00 GMT+0000 (UTC)
and so on...
I can think of 2 ways to avoid it:
First
Create a new variable each time
const requestInterval = 14;
const today = new Date('2019-04-22');
let intervalCorrection = 0;
for (let dayOffset = 0; dayOffset < requestInterval; dayOffset++) {
const inspectedDate = new Date('2019-04-22');
inspectedDate.setDate(today.getDate() + dayOffset);
console.log('iter: ' + dayOffset, ', inspectedDate: ' + inspectedDate);
}
Second
Update the month and year as well before updating date
const requestInterval = 14;
const inspectedDate = new Date('2019-04-22');
const today = new Date('2019-04-22');
let intervalCorrection = 0;
for (let dayOffset = 0; dayOffset < requestInterval; dayOffset++) {
inspectedDate.setMonth(today.getMonth());
inspectedDate.setYear(today.getYear());
inspectedDate.setDate(today.getDate() + dayOffset);
console.log('iter: ' + dayOffset, ', inspectedDate: ' + inspectedDate);
}
Firstly, convert your date to milliseconds.
Secondly, iterate ms in day over your date.
const today = new Date('2019-04-22');
let intervalCorrection = 0;
const millisecsInDay = 1000 * 60 * 60 * 24;
for (let dayOffset = 0; dayOffset < 14; dayOffset++) {
const inspectedDate = new Date(today.getTime() + dayOffset * millisecsInDay);
console.log('iter: ' + dayOffset, ', inspectedDate: ' + inspectedDate);
}

Getting all occurrences of a day in month

i have the first day and last day of the month, the length of the current month i'm looking for a function that will give me all the appearances of any day in this month, i've seen some functions that gives the next occurrence but i want to be able to enter any day and see all is occurrences .. i guess it will be some kind of loop..i'm working on it as we speek but any help would be great..
$scope.recurrenceFields.by_year_day=$filter('date')($scope.fields.times.dateStart, 'yyyy');
$scope.recurrenceFields.by_month=$filter('date')($scope.fields.times.dateStart, 'M');
var correntDay = new Date();
var lastDayOfMonth = new Date(correntDay.getFullYear(), correntDay.getMonth()+1, 0);
var firstDayOfMonth = new Date(correntDay.getFullYear(), correntDay.getMonth(), 1);
function daysInMonth(month,year) {
return new Date($filter('date')($scope.fields.times.dateStart, 'yyyy'), $scope.recurrenceFields.by_month, 0).getDate();
}
Not quite sure what "all the appearances of any day in this month" means, but the following function returns all the occurrences of a particular day in a month given year, month and day number.
/* #param {number} year - calendar year
** #param {number} month - calendar month: 1-Jan, 2-Feb, etc.
** #param {number} dayNumber - day number: 0-Sunday, 1-Monday, etc.
** #returns {Array} Dates for all days in month of dayNumber
*/
function getAllDaysInMonth(year, month, dayNumber) {
var d = new Date(year, --month, 1);
var dates = [];
var daysToFirst = (dayNumber + 7 - d.getDay()) % 7;
var firstOf = new Date(d.setDate(d.getDate() + daysToFirst));
while (firstOf.getMonth() == month) {
dates.push(new Date(+firstOf));
firstOf.setDate(firstOf.getDate() + 7);
}
return dates;
}
// Return array of all Thursdays in July 2015
console.log(getAllDaysInMonth(2015, 7, 4));
// [Thu 02 Jul 2015,
// Thu 09 Jul 2015,
// Thu 16 Jul 2015,
// Thu 23 Jul 2015,
// Thu 30 Jul 2015]
// Get all Tuesdays in February 2000
console.log(getAllDaysInMonth(2000, 2, 2));
// [Tue 01 Feb 2000,
// Tue 08 Feb 2000,
// Tue 15 Feb 2000,
// Tue 22 Feb 2000,
// Tue 29 Feb 2000]
// Get all Sundays in December 2015
console.log(getAllDaysInMonth(2015, 12, 0));
// [Sun 06 Dec 2015,
// Sun 13 Dec 2015,
// Sun 20 Dec 2015,
// Sun 27 Dec 2015]
You can use this service :
angular.module('myApp.services')
.factory('dateUtils', function () {
return {
getIntervals: function (startTimestamp, endTimestamp, interval) {
if(!angular.isNumber(startTimestamp) || !angular.isNumber(endTimestamp) || !angular.isNumber(interval) || startTimestamp===0 || endTimestamp===0) {
return [];
}
var intervals = [];
var currentPeriod = startTimestamp;
while (currentPeriod <= endTimestamp) {
intervals.push(currentPeriod);
var currentPeriodDate = new Date(currentPeriod);
currentPeriodDate.setDate(currentPeriodDate.getDate() + interval);
currentPeriod = currentPeriodDate.getTime();
}
return intervals;
}
};
});
If you want all day between two dates, just use the service :
dateUtils.getIntervals(startDate, endDate, 1);

moment JS get number of weeks in a month

I am trying to calculate number of weeks in a month using moment js. But I am getting wrong results for some months like May 2015 and August 2015.
I am using this code.
var start = moment().startOf('month').format('DD');
var end = moment().endOf('month').format('DD');
var weeks = (end-start+1)/7;
weeks = Math.ceil(weeks);
Is there any prebuilt method in moment JS for getting number of weeks.
I have created this gist that finds all the weeks in a given month and year. By calculated the length of calendar, you will know the number of weeks.
https://gist.github.com/guillaumepiot/095b5e02b4ca22680a50
# year and month are variables
year = 2015
month = 7 # August (0 indexed)
startDate = moment([year, month])
# Get the first and last day of the month
firstDay = moment(startDate).startOf('month')
endDay = moment(startDate).endOf('month')
# Create a range for the month we can iterate through
monthRange = moment.range(firstDay, endDay)
# Get all the weeks during the current month
weeks = []
monthRange.by('days', (moment)->
if moment.week() not in weeks
weeks.push(moment.week())
)
# Create a range for each week
calendar = []
for week in weeks
# Create a range for that week between 1st and 7th day
firstWeekDay = moment().week(week).day(1)
lastWeekDay = moment().week(week).day(7)
weekRange = moment.range(firstWeekDay, lastWeekDay)
# Add to the calendar
calendar.push(weekRange)
console.log calendar
Can be easily done using raw javascript:
function getNumWeeksForMonth(year,month){
date = new Date(year,month-1,1);
day = date.getDay();
numDaysInMonth = new Date(year, month, 0).getDate();
return Math.ceil((numDaysInMonth + day) / 7);
}
You get the day index of the first day, add it to the number of days to compensate for the number of days lost in the first week, divide by 7 and use ceil to add 1 for the simplest overflow in the next week
It display the list of weeks in a month with 'moment.js'.
It has been written in typescript with angular 6+.
Install moment with 'npm i moment'
Inside the ts file.
weeks_in_month() {
let year = 2019; // change year
let month = 4; // change month here
let startDate = moment([year, month - 1])
let endDate = moment(startDate).endOf('month');
var dates = [];
var weeks = [];
var per_week = [];
var difference = endDate.diff(startDate, 'days');
per_week.push(startDate.toDate())
let index = 0;
let last_week = false;
while (startDate.add(1, 'days').diff(endDate) < 0) {
if (startDate.day() != 0) {
per_week.push(startDate.toDate())
}
else {
if ((startDate.clone().add(7, 'days').month() == (month - 1))) {
weeks.push(per_week)
per_week = []
per_week.push(startDate.toDate())
}
else if (Math.abs(index - difference) > 0) {
if (!last_week) {
weeks.push(per_week);
per_week = [];
}
last_week = true;
per_week.push(startDate.toDate());
}
}
index += 1;
if ((last_week == true && Math.abs(index - difference) == 0) ||
(Math.abs(index - difference) == 0 && per_week.length == 1)) {
weeks.push(per_week)
}
dates.push(startDate.clone().toDate());
}
console.log(weeks);
}
Result:
Array of date moments.
[Array(6), Array(7), Array(7), Array(7), Array(3)]
0: (6) [Mon Apr 01 2019 00:00:00 GMT+0530 (India Standard Time),
Tue Apr 02 2019 00:00:00 GMT+0530 (India Standard Time),
Wed Apr 03 2019 00:00:00 GMT+0530 (India Standard Time),
Thu Apr 04 2019 00:00:00 GMT+0530 (India Standard Time),
Fri Apr 05 2019 00:00:00 GMT+0530 (India Standard Time),
Sat Apr 06 2019 00:00:00 GMT+0530 (India Standard Time)]
1: (7) [Sun Apr 07 2019 00:00:00 GMT+0530 (India Standard Time),
Mon Apr 08 2019 00:00:00 GMT+0530 (India Standard Time),
Tue Apr 09 2019 00:00:00 GMT+0530 (India Standard Time),
Wed Apr 10 2019 00:00:00 GMT+0530 (India Standard Time),
Thu Apr 11 2019 00:00:00 GMT+0530 (India Standard Time),
Fri Apr 12 2019 00:00:00 GMT+0530 (India Standard Time),
Sat Apr 13 2019 00:00:00 GMT+0530 (India Standard Time)]
2: (7) [Sun Apr 14 2019 00:00:00 GMT+0530 (India Standard Time),
Mon Apr 15 2019 00:00:00 GMT+0530 (India Standard Time),
Tue Apr 16 2019 00:00:00 GMT+0530 (India Standard Time),
Wed Apr 17 2019 00:00:00 GMT+0530 (India Standard Time),
Thu Apr 18 2019 00:00:00 GMT+0530 (India Standard Time),
Fri Apr 19 2019 00:00:00 GMT+0530 (India Standard Time),
Sat Apr 20 2019 00:00:00 GMT+0530 (India Standard Time)]
3: (7) [Sun Apr 21 2019 00:00:00 GMT+0530 (India Standard Time),
Mon Apr 22 2019 00:00:00 GMT+0530 (India Standard Time),
Tue Apr 23 2019 00:00:00 GMT+0530 (India Standard Time),
Wed Apr 24 2019 00:00:00 GMT+0530 (India Standard Time),
Thu Apr 25 2019 00:00:00 GMT+0530 (India Standard Time),
Fri Apr 26 2019 00:00:00 GMT+0530 (India Standard Time),
Sat Apr 27 2019 00:00:00 GMT+0530 (India Standard Time)]
4: (3) [Sun Apr 28 2019 00:00:00 GMT+0530 (India Standard Time),
Mon Apr 29 2019 00:00:00 GMT+0530 (India Standard Time),
Tue Apr 30 2019 00:00:00 GMT+0530 (India Standard Time)]
EDIT:
NEW and hopefully very correct implementation:
function calcWeeksInMonth(date: Moment) {
const dateFirst = moment(date).date(1);
const dateLast = moment(date).date(date.daysInMonth());
const startWeek = dateFirst.isoWeek();
const endWeek = dateLast.isoWeek();
if (endWeek < startWeek) {
// Yearly overlaps, month is either DEC or JAN
if (dateFirst.month() === 0) {
// January
return endWeek + 1;
} else {
// December
if (dateLast.isoWeekday() === 7) {
// Sunday is last day of year
return endWeek - startWeek + 1;
} else {
// Sunday is NOT last day of year
return dateFirst.isoWeeksInYear() - startWeek + 1;
}
}
} else {
return endWeek - startWeek + 1;
}
}
Outputs the following values for the following dates:
calcWeeksInMonth(moment("2016-12-01")); // 5
calcWeeksInMonth(moment("2017-01-01")); // 6
calcWeeksInMonth(moment("2017-02-01")); // 5
calcWeeksInMonth(moment("2017-03-01")); // 5
calcWeeksInMonth(moment("2017-04-01")); // 5
calcWeeksInMonth(moment("2017-05-01")); // 5
calcWeeksInMonth(moment("2017-06-01")); // 5
calcWeeksInMonth(moment("2017-07-01")); // 6
calcWeeksInMonth(moment("2017-08-01")); // 5
calcWeeksInMonth(moment("2017-09-01")); // 5
calcWeeksInMonth(moment("2017-10-01")); // 6
calcWeeksInMonth(moment("2017-11-01")); // 5
calcWeeksInMonth(moment("2017-12-01")); // 5
calcWeeksInMonth(moment("2018-01-01")); // 5
OLD and very incorrect implementation:
calcWeeksInMonth(date) {
const dateFirst = moment(date).date(1)
const dateLast = moment(date).date(date.daysInMonth())
const startWeek = dateFirst.week()
const endWeek = dateLast.week()
if (endWeek < startWeek) {
return dateFirst.weeksInYear() - startWeek + 1 + endWeek
} else {
return endWeek - startWeek + 1
}
}
This seems to output correct results, feedback welcome if there is something I missed!
function getWeekNums(momentObj) {
var clonedMoment = moment(momentObj), first, last;
// get week number for first day of month
first = clonedMoment.startOf('month').week();
// get week number for last day of month
last = clonedMoment.endOf('month').week();
// In case last week is in next year
if( first > last) {
last = first + last;
}
return last - first + 1;
}
javaScript version here
var year = 2021
var month = 6
var startDate = moment([year, month])
//Get the first and last day of the month
var firstDay = moment(startDate).startOf('month')
var endDay = moment(startDate).endOf('month')
//Create a range for the month we can iterate through
var monthRange = moment.range(firstDay, endDay)
//Get all the weeks during the current month
var weeks = []
var indexOf = [].indexOf;
monthRange.by('days', function (moment) {
var ref;
if (ref = moment.week(), indexOf.call(weeks, ref) < 0) {
return weeks.push(moment.week());
}
});
var calendar, firstWeekDay, i, lastWeekDay, len, week, weekRange;
calendar = [];
for (i = 0, len = weeks.length; i < len; i++) {
week = weeks[i];
// Create a range for that week between 1st and 7th day
firstWeekDay = moment().week(week).day(0);
lastWeekDay = moment().week(week).day(6);
weekRange = moment.range(firstWeekDay, lastWeekDay);
// Add to the calendar
calendar.push(weekRange);
}
This is the best way out , works well
moment.relativeTime.dd = function (number) {
// round to the closest number of weeks
var weeks = Math.round(number / 7);
if (number < 7) {
// if less than a week, use days
return number + " days";
} else {
// pluralize weeks
return weeks + " week" + (weeks === 1 ? "" : "s");
}
}
Source:How to get duration in weeks with Moment.js?
I have not seen a solution that works in all circumstances. I tried all of these but they all are flawed in one way or another. Ditto with several moment.js github threads. This was my crack at it:
getNumberOfWeeksInMonth = (momentDate) => {
const monthStartWeekNumber = momentDate.startOf('month').week();
const distinctWeeks = {
[monthStartWeekNumber]: true
};
let startOfMonth = momentDate.clone().startOf('month');
let endOfMonth = momentDate.clone().endOf('month');
// this is an 'inclusive' range -> iterates through all days of a month
for (let day = startOfMonth.clone(); !day.isAfter(endOfMonth); day.add(1, 'days')) {
distinctWeeks[day.week()] = true
}
return Object.keys(distinctWeeks).length;
}
function weeksInMonth(date = null){
let firstDay = moment(date).startOf('month');
let endDay = moment(date).endOf('month');
let weeks = [];
for (let i = firstDay.week(); i <= endDay.week(); i++){
weeks.push(i)
}
return weeks;
}
Here is a simple way of doing it (based on a solution posted above):
const calcWeeksInMonth = (momentDate) => {
const dateFirst = moment(momentDate).date(1)
const dateLast = moment(momentDate).date(momentDate.daysInMonth())
const startWeek = dateFirst.isoWeek()
const endWeek = dateLast.isoWeek()
if (endWeek < startWeek) {
// cater to end of year (dec/jan)
return dateFirst.weeksInYear() - startWeek + 1 + endWeek
} else {
return endWeek - startWeek + 1
}
}
As far as I can tell, it works correctly for any date thrown at it, but feedback is always welcome!
Throwing this into the mix
import moment from "moment";
export const calcWeeksInMonth = date => {
let weekMonthEnds = moment(date)
.date(moment(date).daysInMonth())
.week();
let weekMonthStarts = moment(date)
.date(1)
.week();
return weekMonthEnds < weekMonthStarts
? moment(date).isoWeeksInYear() - weekMonthStarts + 1
: weekMonthEnds - weekMonthStarts + 1;
};
var month = moment().month();
var startOfMonth = month.startOf("month");
var endOfMonth = month.endOf("month");
var startWeekNumber = startOfMonth.isoWeek();
var endWeekNumber = endOfMonth.isoWeek();
var numberOfWeeks = (endWeekNumber - startWeekNumber + 1);
console.log(numberOfWeeks);
If you have selectedDate value that is give you opportunity to detect which month is active now:
private calculateNumberOfWeeks(): number {
const end = moment(this.selectedDate).endOf('month');
const startDay = moment(this.selectedDate)
.startOf('month')
.day();
const endDay = end.day();
const endDate = end.date();
return (startDay - 1 + endDate + (endDay === 0 ? 0 : 7 - endDay)) / 7;
}
/UPDATE/
Solution below did not take in consideration jump to the new year.
Here is the improved solution.
const getNumberOfWeeksInAMonth = (currentMoment: moment.Moment) => {
const currentMomentCopy = cloneDeep(currentMoment)
const startOfMonth = currentMomentCopy.startOf('month')
const startOfISOWeek = startOfMonth.startOf('isoWeek')
let numberOfWeeks = 0;
do {
numberOfWeeks++
MomentManager.addWeek(startOfISOWeek)
} while (currentMoment.month() === startOfISOWeek.month())
return numberOfWeeks;
}
I have found another solution with momentjs.
const getNumberOfWeeksInMonth = (moment: moment.Moment) => {
const startWeek = moment.startOf('month').isoWeek()
const endWeek = moment.endOf('month').isoWeek()
return endWeek - startWeek + 1
}

Printing 3 year calendar in months staring from the current month

I am getting the current date in javascript and then I convert it to the current month. Based on the current month (9 now), I want to print the month calendar for the last 3 years backwards. So, if we have September 2013, the following has to be printed:
08 09 10 11 12 2010
01 02 03 04 05 06 07 08 09 10 11 12 2011
01 02 03 04 05 06 07 08 09 10 11 12 2012
01 02 03 04 05 06 07 08 2013
I have a general idea how to print the first line, but I'm struggling how to print the rest of the calendar. Here is my code for the first line (2013):
function printCalendarRows(){
var d = new Date();
var n = (d.getMonth()) + 1;
var twelve = 12;
for(var i = n; i <= 12; i++){
for(var j = 12; j >= n; j--){
console.log(i);
console.log(j);
}
}
}
Any recommendations? Thanks
function calRows() {
var date,
now = new Date(),
str = "";
for (var i = -37;i++;) {
date = new Date(now.getFullYear(), now.getMonth() + i - 1, 1)
month = ("0" + (date.getMonth() + 1)).slice(-2);
str += month + " " + (+month % 12 == 0 ? date.getFullYear() + "\n" : "")
}
return str + date.getFullYear();
}
console.log (calRows()) /*
08 09 10 11 12 2010
01 02 03 04 05 06 07 08 09 10 11 12 2011
01 02 03 04 05 06 07 08 09 10 11 12 2012
01 02 03 04 05 06 07 08 2013 */
Heres a Fiddle
Or if you prefer, the same without assigning a new Date object in the loop.
function calRows() {
var date,
now = new Date(),
first = new Date(now.getFullYear(), now.getMonth() -37, 1),
monthYear = [first.getMonth(),first.getFullYear()]
str = "";
for (var i = -37;i++;) {
month = ("0" + (++monthYear[0])).slice(-2);
str += month + " " + (+month % 12 == 0 ? (monthYear[0]=0,monthYear[1]++) + "\n" : "")
}
return str + monthYear[1]
}
Check if this is what you want
function printCalendarRows(){
var d = new Date();
var o = new Date();
o.setMonth( (d.getMonth()) - 36); //or o.setFullYear( (d.getFullYear()) - 3);
var currnt;
while (o < d)
{
currnt = o.getMonth();
console.log(currnt);
if (currnt == 11)
{
console.log(o.getFullYear());
}
o.setMonth(currnt+1);
}
if (d.getMonth() != 11)
{
console.log(d.getFullYear());
}
alert("Date:"+ d + "Month:" + d.getMonth());
}
I would use momentjs:
function printCalendarRows(){
var d = moment().subtract('months', 37);
var y = d.format("YYYY");
var n = moment().format("MM/YYYY");
var log = "";
while(d.format("MM/YYYY") != n) {
if (d.format("YYYY") != y) {
console.log(log + y + "\r\n");
y = d.format("YYYY");
log = "";
}
log += d.format("MM") + " ";
d = d.add("months", 1);
}
console.log(log + d.format("YYYY"));
}
printCalendarRows();
working DEMO

Categories