compare only month not date and year in mongodb - javascript

I want to find elements from db which dateOfSale month is equal to selected month.
for example:
elem1 :- dateOfSale = 06-02-2023
elem2 :- dateOfSale = 06-02-2022
elem3 :- dateOfSale = 06-0-2023
and I want to compare only month means which element that month will be equal to 2.
so, the expected results will be:- elem1 and elem2 (no matters what's the year only month should be matched.)

Related

Recurring date using dayjs with dayrs-recur

I’m willing to create a recurring date based on "nth weekday of month"
Here is my solution work when I select current Date
let dates = {};
const currentDate = dayjs();
const recurrence = currentDate
.recur(dayjs().add(4, "month"))
.every("Wednesday")
.daysOfWeek()
.every(currentDate.monthWeekByDay())
.weeksOfMonthByDay();
recurrence.all().forEach((date) => {
dates[date.format("YYYY-MM-DD")] = { selected: true, };
});
// dates = ["2022-09-21","2022-10-19","2022-11-16","2022-12-21","2023-01-18"]
but if put last day of this month which is 30
let dates = {};
const lastDayofMonth = dayjs().endOf("month");
const recurrence = lastDayofMonth
.recur(dayjs().add(4, "month"))
.every("Friday")
.daysOfWeek()
.every(lastDayofMonth.monthWeekByDay())
.weeksOfMonthByDay();
I was expecting to get
["2022-09-30","2022-10-28","2022-11-25","2022-12-30"..]
instead of
["2022-09-30","2022-12-30"]
Here is demo
Am I missing something ?
Thanks in advance
It possible to create a recurring date based on "nth weekday of month" with dayjs and dayjs-recur as all months as different number of weeks
But there are some challenges:
A month has 4 weeks on average (some months have few or no days for fifth week)
Due to this there may be cases where there is no fifth week or the fifth week doesn't have the nth weekday
To resolve this
If you are getting an nth weekday of month where the week is the last week of the month (could be 4th/5th week)
Get both the nth weekday of month for the last week (5th) and the fourth (4th) week
From the list of dates returned filter if dates for a month occur multiple times and select the latest/greatest one
The filtered result should have the nth weekday of month where the week is the last week of the month
Demo
Below is a link to a working demo forked from #Achraf's demo on code sandbox
Demo Link
Code Example
const lastDayofMonth = dayjs().endOf("month");
const recurrence = lastDayofMonth
.recur(dayjs().add(4, "month"))
.every("Friday")
.daysOfWeek()
.every([3, 4])
.weeksOfMonthByDay();
// filter recurrence
const months = {};
recurrence.all().forEach((date) => {
months[date.month()] = date;
})
// get filtered dates
const filteredDates = Object.values(months);
// formot date into dates object
filteredDates.forEach((date) => {
dates[date.format("YYYY-MM-DD")] = { selected: true, color: "#2FB0ED" };
});
console.log("dates", dates);
// ["2022-09-30","2022-10-28","2022-11-25","2022-12-30"..]

MomentJS - how to select all days of the week by name?

How to sellect all same weekdays by using momentJS? Ex: All Mondays of current month. If the day is 15th day of the month, there are two Mondays in that month, from 0 to 15th day of the month. Maybe it is some kind of looping, because momenthJS should return two dates-one for first Monday and second for second Monday in the given range and so on.
Or is there any other way to do this by using any other JavaScript library?
As you said a loop can solve this problem
move 4 weeks before from the date you have e.g. if we were on the last monday of the month we move to the first monday of the month or a previous date (if we move to the previous month we can still get the correct dates by doing more iterations)
get the month of the date you have (all the dates you get should have the same month)
move forward from the initial date computed above a week each time and check if the new date has the same month as the input date
function weekdaysFromMonth (date) {
// all the weekdays previous/next to date should be
// 7 days apart and also have the same month
var month = date.get('month')
// make sure that the start date is 4 weeks before now
// we might go to the previous month but anyway we'll
// get the correct dates by doing more iterations
var start = moment(date).subtract(4 * 7, 'days')
var dates = []
for (var i = 0; i < 10; i += 1) {
start.add(7, 'days')
if (start.get('month') === month) {
dates.push(moment(start))
}
}
return dates
}
document.write(
JSON.stringify(
weekdaysFromMonth(moment()), null, ' '
)
)
<script src="http://momentjs.com/downloads/moment.js"></script>

Get month name from two digit month number

I want to get month name from two digit month number (ex- 09). I tried with this code. But it doesn't work. The code give current month name only. What are the correct code for it?
var formattedMonth = moment().month('09').format('MMMM');
While there's nothing wrong with Kevin's answer, it is probably more correct (in terms of efficiency) to obtain the month string without going through a moment object.
var monthNum = 9; // assuming Jan = 1
var monthName = moment.months(monthNum - 1); // "September"
var shortName = moment.monthsShort(monthNum - 1); // "Sep"
You want to pass the month when you create the Moment object:
var formattedMonth = moment('09', 'MM').format('MMMM'); // September
moment(
'09', // Desired month
'MM' // Tells MomentJs the number is a reference to month
).format('MMMM') // Formats month as name
You need to pass the month as a number, not text - so...
var formattedMonth = moment().month(9).format('MMMM');
console.log(formattedMonth)
Result:
October
For those looking to do it and changing languages (locale), this is what I did
let month = moment().month(09).locale('pt-br').format('MMMM');

MomentJS - How to get last day of previous month from date?

I'm trying to get last day of the previous month using:
var dateFrom = moment(dateFrom).subtract(1, 'months').format('YYYY-MM-DD');
Where:
dateFrom = 2014-11-30
But after using
subtract(1, 'months')
it returns date
DATE_FROM: "2014-10-30"
But last day of the 10'th month is 31.
How can I solve i please?
Many thanks for any help.
Simply add a endOf('month') to your calls:
var dateFrom = moment(dateFrom).subtract(1,'months').endOf('month').format('YYYY-MM-DD');
http://jsfiddle.net/r42jg/327/
An even easier solution would be to use moment.date(0). the .date() function takes the 1 to n day of the current month, however, passing a zero or negative number will yield a dates in the previous month.
For example if current date is February 3rd:
var _date = moment(); // 2018-02-03 (current day)
var _date2 = moment().date(0) // 2018-01-31 (start of current month minus 1 day)
var _date3 = moment().date(4) // 2018-02-04 (4th day of current month)
var _date4 = moment().date(-4) // 2018-01-27 (start of current month minus 5 days)
console.log(_date.format("YYYY-MM-DD"));
console.log(_date2.format("YYYY-MM-DD"));
console.log(_date3.format("YYYY-MM-DD"));
console.log(_date4.format("YYYY-MM-DD"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.js"></script>
Last month's First date and last month's last date from the current date basis. The Format of the date changes depending upon. (DD-MM-YYYY)
console.log("last month first date");
const lastmonthlastdate=moment().subtract(1, 'months').startOf('month').format('DD-MM-YYYY')
console.log(lastmonthlastdate);
console.log("lastmonth last date");
const lastmonthfirstdate=moment().subtract(1, 'months').endOf('month').format('DD-MM-YYYY')
console.log(lastmonthfirstdate);
moment().subtract(1, 'months').endOf('month').format('YYYY-MM-DD')
You can get the first day of the month then subtract 1 day to get the last day of the previous month.
const monthyear = moment().format('YYYY-MM')
const firstDay = moment(monthyear + "-01").format("YYYY-MM-DD");
// Subtract 1 day to get the end of the previous month
const dateTo = moment(firstDay).subtract('1', 'days').format("YYYY-MM-DD");

JavaScript - convert to string using array index

I got this code from a book and I don't understand how this statement "mm=months[mm]" convert to month name string:
function init(){
var panel = document.getElementById("panel");
var days=["sun","mon","tue","wed","thur","fri","sat"];
var months=["jan","feb","mar","apr","may","jun",
"jul","aug","sep","oct","nov","dec"];
var now = new Date();
var yy = now.getFullYear();
var mm = now.getMonth();
var dd = now.getDate();
var dy = now.getDay();
mm=months[mm]; //convert to month name string
dy=days[dy]; //convert to month name string
var str = dy+","+mm","+dd+","+yy;
panel.innerHTML+="us date string: "+str;
str = dy+","+dd+" "+mm+","+yy;
panel.innerHTML+="<br>uk date string: "+str;
}
window.onload=init();
My question is this what exactly does the mm=months[mm] and dy=days[dy] (convert to month or day name string) do. I don't understand how this statement "mm=months[mm]" convert to month name string, when months is an array. Is this just some build in function of an array?
mm is a number at the beginning of the statement mm=months[mm], so therefore it returns the mmth value in the months array which is a string. In JavaScript variables are not strictly typed so it then inserts this string into the variable mm
mm is a number from 0-11 that represents the month specific to the date object you retrieved it from. months is an array containing the names of all the months. If you say mm = months[mm], you're saying that mm equals the string at position mm in the months array. It's confusing, because they're using the same variable name. It might have been better to do something like this:
var mm = now.getMonth();
alert(mm); // will alert 6
var monthName = months[mm]; // will alert July, which is position 7 in the months array
The reason mm is six is because the months for some reason are 0-indexed, meaning they start at 0 and go to 11; January would be 0, and December 11.
days is an array. Given index dy=0, days[dy] returns "sun", which is the 0th value in the array. Similarly, given index dy=1, days[dy] returns "mon", which is the 1st value in the array. And so on.
Same concept for months.
But the correct answer should be "use some built-in function in Javascript or jQuery". See this post for more details. Rolling your own datetime conversion functions is almost certainly going to come back and bite you in the long run.
Assume the date is 08 and month is july .
var yy = now.getFullYear();
var mm = now.getMonth(); // month is 7 now
var dd = now.getDate(); // dd is 8 now
var dy = now.getDay();
Now,
mm=months[mm];
means,
mm = months[7];
// in months array, at seventh index we have july,
so mm is july.
No its not converting but using value from array based on index.
mm=month[mm] take the value at the index mm (returned by now.getMonth()) in the months array and puts it in the mm variable. That id the same thing for dy=days[dy].
I recognize that the code is badly written. mm2=month[mm] and use mm2 after (instead of the "new" mm) should be written instead.

Categories

Resources