I need to know how I would obtain the last Monday of each month, since in the program that I have to do, that last Monday of each month I must generate interest, but I don't know how I could calculate it.
try to get the total days of the month and subtract 7 days but obviously the result will not always be a Monday.
DateTime fechaHoy = (DateTime)fechahoy.Value.Date;
DateTime fechabono = FechaAbono.Value.Date;
int anyo = fechabono.Year;
int mes = fechabono.Month;
int dias = DateTime.DaysInMonth(anyo, mes);
int anyoHoy = fechaHoy.Year;
int mesHoy = fechaHoy.Month;
int diasHoy = DateTime.DaysInMonth(anyoHoy, mesHoy);
int totaldiashoy = DateTime.DaysInMonth(anyoHoy, mesHoy);// 31 dias
int totaldias = totaldiashoy - 7;
The answers you have received make use of a loop. I am going to add one that is not, and it is also generic to search for any day of the week. The last day of the month is simply calculated, and with whatever day of the week it is, it is calculated which is the previous day of the week that interests us.
This works because the DayOfWeek enumeration assigns an integer to each day of the week, with Sunday being 0 and so on until Saturday is 6.
The way to call it is as follows:
If you want to know the day number Monday of the month, use the following function:
Cheers
The last Monday of any month would be:
When
fecha
it is the last day of the month (and assuming that Monday is valid1
and Sunday is valid0
). Now your problem is to get the last day of the month, which is as simple as going to the first day of the next month and subtracting one day:So, the last Monday of January 2019 was:
The code above shows:
One way to do this would be to first get the last week of the month you want to get, and then get the Monday of that week like this:
what you can do is go back through the days ( for efficiency reasons ) and the first Monday you find is your last Monday of the month: