I have a list of dates and want to check how often occurs weekend, weeks and month in the list
I have a list of dates from 1 year like 2023-01-01 until 2024-01-01
["2023-01-31T23:00:00.000Z", "2023-02-01T23:00:00.000Z", "2023-02-02T23:00:00.000Z", "2023-02-03T23:00:00.000Z", …]
How can I convert this that I get a object of this:
day: 12,
weekend: 5,
month: 5
3
Answers
Add all your data inside an array, and then using the
forEach
method, iterate over each date string.There are 3 main variables.
dayCount
to count the total number of days.weekendCount
to count the number of weekends.monthCount
to count the number of months.Count the total number of days by increasing the
dayCount
.If the date falls on a weekend (Saturday or Sunday), we increase
weekendCount
to keep track of the total number of weekends.If the date is the first day of the month, increase
monthCount
to keep track of the number of months.You’re welcome, here’s your final code.
You can make your code a little bit shorter by using
filter
method, and thedayCount
is simply set to the length of thedateList
array (guessing that each date is a new day).You can make your code even shorter by using an arrow function expression, and directly assigning variables.
use momentjs to manipulate date in javascript
Date of Month :
Day of Week :
You can achieve this by following the steps below:
Parse each date string in your array into a
Date
object.Keep three counters: one for days, one for weekends, and one for months.
Check each date. If it’s a weekend (Saturday or Sunday), increment the weekend counter.
Keep track of the current month. When the month changes, increment the month counter.
Finally, return an object containing the three counts.
//example