Get weekdays within a month
With the help of this answer, I was able to accomplish this.
let calendar = NSCalendar.currentCalendar()
let normalizedStartDate = calendar.startOfDayForDate(NSDate().startOfMonth)
let normalizedEndDate = calendar.startOfDayForDate(NSDate().endOfMonth)
var dates = [normalizedStartDate]
var currentDate = normalizedStartDate
repeat {
currentDate = calendar.dateByAddingUnit(NSCalendarUnit.Day, value: 1, toDate: currentDate, options: .MatchNextTime)!
dates.append(currentDate)
} while !calendar.isDate(currentDate, inSameDayAsDate: normalizedEndDate)
let weekdays = dates.filter { !calendar.isDateInWeekend($0) }
weekdays.forEach { date in
print(NSDateFormatter.localizedStringFromDate(date, dateStyle: .FullStyle, timeStyle: .NoStyle))
}
And it works!
Monday, February 1, 2016
Tuesday, February 2, 2016
Wednesday, February 3, 2016
Thursday, February 4, 2016
Friday, February 5, 2016
Monday, February 8, 2016
Tuesday, February 9, 2016
Wednesday, February 10, 2016
Thursday, February 11, 2016
Friday, February 12, 2016
Monday, February 15, 2016
Tuesday, February 16, 2016
Wednesday, February 17, 2016
Thursday, February 18, 2016
Friday, February 19, 2016
Monday, February 22, 2016
Tuesday, February 23, 2016
Wednesday, February 24, 2016
Thursday, February 25, 2016
Friday, February 26, 2016
Monday, February 29, 2016
How to get all dates and weekdays in current month in flutter
The lastDayOfMonth
is a single date, therefore using lastDayOfMonth.weekDay
gives a single day based on lastDayOfMonth
. We can add duration on lastDayOfMonth
and find day name.
final currentDate =
lastDayOfMonth.add(Duration(days: index + 1));
This will provide update date based on index
. I am using intl
package or create a map to get the day name.
A useful answer about date format.
Row(
children: List.generate(
lastDayOfMonth.day,
(index) => Padding(
padding: const EdgeInsets.only(right: 24.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
"${index + 1}",
),
() {
final currentDate =
lastDayOfMonth.add(Duration(days: index + 1));
final dateName =
DateFormat('E').format(currentDate);
return Text(dateName);
}()
],
),
),
),
),
How would I get the amount of weekdays in a month with LocalDate - Java
If desired, see optimized brute-force solution at the end
Here is a non-brute-force implementation to calculate week days (Mon-Fri) in a month.
It uses YearMonth
instead of LocalDate
, since the day-of-month value is meaningless to the calculation.
public static int weekDaysInMonth(YearMonth yearMonth) {
int len = yearMonth.lengthOfMonth(); // 28-31, supporting leap year
int dow = yearMonth.atDay(1).getDayOfWeek().getValue(); // 1=Mon, 7=Sun
return (dow <= 5 ? Math.min(len - 8, 26 - dow) : Math.max(len + dow - 16, 20));
}
Here is an overload taking a LocalDate
, so it's easy to call if that's what you have.
public static int weekDaysInMonth(LocalDate date) {
return weekDaysInMonth(YearMonth.from(date));
}
Test
System.out.println(weekDaysInMonth(LocalDate.parse("2018-04-15"))); // April 15, 2018
System.out.println(weekDaysInMonth(YearMonth.of(2018, 5))); // May 2018
Output
21
23
Explanation of Formula
The formula in the return
statement was created by examining the expected return value for every combination of len
(number of days in month, 28 - 31) and dow
(day-of-week of first day of month, 1=Mon - 7=Sun):
| 1 2 3 4 5 6 7
| Mo Tu We Th Fr Sa Su
---+----------------------------
28 | 20 20 20 20 20 20 20
29 | 21 21 21 21 21 20 20
30 | 22 22 22 22 21 20 21
31 | 23 23 23 22 21 21 22
Explanation for dow <= 5
(Mon-Fri)
Initially there are len - 8
weekdays, i.e. we subtract the 4 weekends that always exist in a month.
As we get to Thursday and Friday, we need to cap that for the 1 or 2 weekend days we lose. If you look at the 31-day row, we cap it at 26 - dow
, i.e. for Friday (dow=5
) we cap at 21
, and for Thursday (dow=4
) we cap at 22
. For Monday-Wednesday, we also cap, but cap is equal to or higher than initial calculation, so it doesn't matter.
Capping is done using min(xxx, cap)
method, so we get:
min(len - 8, 26 - dow)
Explanation for dow >= 6
(Sat-Sun)
You can see a small triangle in the lower-right corner. If we extend that pattern, we get:
| 4 5 6 7
---+---------------
28 | 16 17 18 19
29 | 17 18 19 20
30 | 18 19 20 21
31 | 19 20 21 22
As a formula, that is len + dow - 16
.
Comparing that to original grid, numbers bottom out at 20
, which is done using max(xxx, bottom)
method, so we get:
max(len + dow - 16, 20)
Conclusion
Finally we combine the two using ternary conditional operator:
dow <= 5 ? min(len - 8, 26 - dow) : max(len + dow - 16, 20)
Full Java statement is then:
return (dow <= 5 ? Math.min(len - 8, 26 - dow) : Math.max(len + dow - 16, 20));
Brute-Force Solution
If you prefer a brute-force solution, you can ease it by skipping the first 4 weeks that always exists in a month:
public static int weekDaysInMonth(LocalDate refDate) {
LocalDate firstOfMonth = refDate.withDayOfMonth(1);
LocalDate nextMonth = firstOfMonth.plusMonths(1);
int days = 20;
for (LocalDate date = firstOfMonth.plusDays(28); date.isBefore(nextMonth); date = date.plusDays(1))
if (date.getDayOfWeek().getValue() <= 5) // 1=Mon - 5=Fri, i.e. not 6=Sat and 7=Sun
days++;
return days;
}
Get number of weekdays in a given month
Some basic code:
$month = 12;
$weekdays = array();
$d = 1;
do {
$mk = mktime(0, 0, 0, $month, $d, date("Y"));
@$weekdays[date("w", $mk)]++;
$d++;
} while (date("m", $mk) == $month);
print_r($weekdays);
Remove the @
if your PHP error warning doesn't show notices.
print first 10 working days in a month using python
Here's an example:
import datetime
date = datetime.datetime.strptime("MAR-21", "%b-%y")
weekdaycount = 0
while weekdaycount < 10:
if date.weekday() in [0,1,2,3,4]:
print(date)
weekdaycount += 1
date += datetime.timedelta(days=1)
how to get weekday and weekend count for months?
Use EXTRACT
with the date part isodow
. This returns a value of 1 to 7 for Monday through Sunday.
SELECT
u.fname,
MONTH(e.eventDate),
COUNT(*) FILTER (WHERE EXTRACT(idodow FROM e.eventDate) < 6) AS WeekdayCount,
COUNT(*) FILTER (WHERE EXTRACT(idodow FROM e.eventDate) IN (6, 7)) AS WeekendCount,
FROM users u
LEFT JOIN eventcal e ON e.primary = u.username
GROUP BY
u.fname,
MONTH(e.eventDate);
Note also that a left join from users
to the eventcal
table would seem to make the most sense here, not the reverse.
How to get a list of week days in a month?
Well, how about:
public static List<DateTime> GetDates(int year, int month)
{
return Enumerable.Range(1, DateTime.DaysInMonth(year, month))
.Select(day => new DateTime(year, month, day))
.Where(dt => dt.DayOfWeek != DayOfWeek.Sunday &&
dt.DayOfWeek != DayOfWeek.Saturday)
.ToList();
}
Related Topics
How to Use Tap Gesture in Accessibility in Swift
Give Thumbnail Image with Uiactivityviewcontroller
How to Get the Index (String.Index) Value from the Cursor Position of a Uitextview Element in Swift
Exc_Breakpoint (Sigtrap) on Production Version Only
Get Total Include Months Between 2 Date in Swift
Swiftui Animation and Subsequent Reverse Animation to Original State
Generate a Hmac Swift Sdk8.3 Using Cchmac()
Uitableviewcell Custom Class - Reload Cell Height After Change in Subview Height Constraint
The Array Value Should Be Sort Like (Alphabetic, Numbers and Special Characters)
How Should Secure Transport Tls Be Used with Bsd Sockets in Swift
Table View Controller Duplicate Itself in iOS Swift
iOS Pass Data Back from Viewcontroller2 to Viewcontroller 1 with Presentmodalsegue
Increment Tab Bar Badge W/ Uialertaction Swift
How to Remove Single Object in Array from Multiple Matching Object