determine maximum number of days in particular month - c#

from razor view I'm sending selected month and year to the controller using jquery.
Inside controller I'm receiving those selected values and create datetime properties
public ActionResult Index(int year, int month)
{
Date1 = new DateTime(year, month, 1);
Date2 = new DateTime(year, month, 31);
...
}
Some months has 31 day, some 30 and feb. has 28 (inside leap year 29) days.
My question is:
How can I recognize those months and based on that set appropriate max month day inside Date2 variable?

You could use the DaysInMonth method on DateTime:
Date2 = new DateTime(year, month, DateTime.DaysInMonth(year, month));

You want DateTime.DaysInMonth(year, month)

Related

C# How to get the "greyed" days of a month DateTime

In Windows 10 calendar, as an example, we find an grid of 7x6 days that represents each day of the month, but is obvious that no month has 42 days, so "overflowed" days, by any means, the days that show in the grid but isn't of current month is greyed out as a day of another month. Is there some easy way to get these days on C# with DateTime class?
For example, in 2020/08, the "greyed days" is: 26, 27, 28, 29, 30, 31 (days of the previous month) and 1, 2, 3, 4, 5 (days of the next month).
In case that isn't clear, this is a screenshot showing the days that i'm referring
I couldn't find any question that relates my question.
Edit:
The best answer is by #ChilliPenguin, this is my implementation:
public static MonthGrayDays GrayDays(this DateTime time) {
List<DateTime> before = new List<DateTime>();
List<DateTime> after = new List<DateTime>();
DateTime firstDay = new DateTime(time.Year, time.Month, 1);
DateTime prevMonth = firstDay.AddDays(-1);
DateTime nextMonth = firstDay.AddMonths(1);
int daysInMonth = DateTime.DaysInMonth(time.Year, time.Month);
for (int a = 0; a < (int)firstDay.DayOfWeek; a++)
{
before.Add(prevMonth.AddDays(-a));
}
before.Reverse();
int count = before.Count();
for (int b = 0; b < 42 - count - daysInMonth; b++)
{
after.Add(nextMonth.AddDays(b));
}
return new MonthGrayDays {previousMonth = before, nextMonth = after};
}
This is an Extension method of DateTime class, it returns a custom class that returns the dates before and after the month, the class is implemented as follow:
public class MonthGrayDays {
public List<DateTime> previousMonth;
public List<DateTime> nextMonth;
}
To use the extension method, just call:
DateTime now = new DateTime(2020, 8, 1);
foreach (DateTime date in now.GrayDays().previousMonth) {
Console.WriteLine(date.Day);
}
Console.WriteLine("/");
foreach (DateTime date in now.GrayDays().nextMonth) {
Console.WriteLine(date.Day);
}
I don't think there's an automatic solution, but the logic is simple enough to step through. The most important thing is the DateTime.DayOfWeek property. It returns a DayOfWeek enum value corresponding to Sunday through Saturday which can be cast to an int ranging from 0 to 6 accordingly.
Take your month and construct a DateTime object corresponding to the 1st of the month. Now take its DayOfWeek and cast to int, and now you have the number of grey days at the top of the calendar. Getting the number from the end of the month is equally simple. Build a DateTime object for the last day of the month and cast its DayOfWeek to an int and subtract from 6 to get the number of grey days.
If you need to dates for those grey days, start at first day of the month and subtract 24 hours to get the last day of the previous month. The grey days for the end of the calendar can be assumed to start at 1.
Using the DateTime and DateTimeOffset Structs you could calculate for the first day of the month's type of day using the Day of week function. This would return an enum. If you convert the enum to an int(note, 0 = sunday, which does correlate with the windows calender) you would be able to loop back to get those dates. I would recommend using a List to store these dates, but I do not know your current situation :)
for (int a = 0; a < (int)FirstDay.DayOfWeek; a++)
{
graydays.Add(prevmonth.AddDays(-a));
}
To get the dates after the current month we could get the count of the days listed, the number of days in the month, and the grid area(42 in this case) to calculate the amount of days after the month that we need to consider.
int count = graydays.Count();
for (int b = 0; b < 42 - count - daysinmonth; b++)
{
graydays.Add(LastDayOfMonth.AddDays(b));
}
Note, To get the daysinmonth, you need to use the DateTime.DaysInMonth() function, and to get the Last day, just add 1 month to the first day, and then subtract a day.

C# Get last day of previous month given a month and year

I'm trying to create a method that returns me a DateTime object.
This date should be the last day of the previous month (month is given by me).
Example:
Month: january (1)
Year: 2019
What I need: 31/12/2018
This is what I have
public DateTime getLastDayPrevMonth(int month, int year)
{
DateTime date = new DateTime();
date.Month == month;
date.Year == year;
date.AddMonths(-1);
date.Day = DateTime.DaysInMonth(date.Year,date.Month);
return date;
}
but it returns the error:
Only assignment, call, increment, decrement, and new object expressions can be used as a statement
What am I doing wrong?
How about:
public DateTime GetLastDayPrevMonth(int month, int year)
{
return new DateTime(year, month, 1).AddDays(-1);
}
This creates a new DateTime Object for the first day in the given Month/Year. Then it subtracts one day off of the first day of the month, leaving you with the last day of the previous month.
you can get Current Date like
var CurrentDate= DateTime.Now;
and first day of Current Month like
var FirstdayOfThisMonth= new DateTime(CurrentDate.Year, CurrentDate.Month, 1);
and you can add -1 that will return last day of previous month like
var lastDayOfLastMonth = FirstdayOfThisMonth.AddDays(-1);

Calculate Last Day of the Next Month

I am attempting to use the DateTime function in C# to calculate the last day of next month.
For example, today is December 17th 2015. I want the DateTime function to return January 31st 2016 (the last day of next month).
I am using the following to calculate the first day of next month (this works):
DateTime firstDayNextMonth = DateTime.Today.AddDays(-DateTime.Now.Day+1).AddMonths(1);
DateTime reference = DateTime.Now;
DateTime firstDayThisMonth = new DateTime(reference.Year, reference.Month, 1);
DateTime firstDayPlusTwoMonths = firstDayThisMonth.AddMonths(2);
DateTime lastDayNextMonth = firstDayPlusTwoMonths.AddDays(-1);
DateTime endOfLastDayNextMonth = firstDayPlusTwoMonths.AddTicks(-1);
Demo: http://rextester.com/AKDI52378
//system date or any date u want this case it is a calendar picker - 22/03/2016
DateTime today = dtpFrom.Value;
//Add a month to your date example , it now becomes - 22/04/2016
DateTime endOfMonth = new DateTime(today.Year, today.Month,today.Day).AddMonths(1);
//Get the last date off the above which is - 30
int getlastday = DateTime.DaysInMonth(endOfMonth.Year, endOfMonth.Month);
//Now set the date to the value which will be the last day off the next month - 30/04/2016
DateTime newDate = new DateTime(endOfMonth.Year, endOfMonth.Month, getlastday);
DateTime.DaysInMonth(DateTime.Now.AddMonths(1).Year, DateTime.Now.AddMonths(1).Month);
var lastDayInNextMonth = DateTime.DaysInMonth(DateTime.Now.AddMonths(1).Year, DateTime.Now.AddMonths(1).Month );
# Ben : DateTime.Now.AddMonths(1) will add 1 month to the current date not substract 11 months.
DateTime.Now.AddMonths(1).Year will give 2016 not 2015 refer the attached image
try this:
int Day= DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month+1>12 ? 01 : DateTime.Now.Month+1 );

Setting A particular Day in a date

I am using Calender Extender Control in the AjaxControlToolkit. There are basically 2 controls of date : Start Date and End date (both associated with calender extender). Based on start Date selected, I populate date in the end date field like adding no of months or days. But like I have been able to add months, but also wants to set a particular day of that month which I am unable to do.
Example:
Today date is 18 Dec 2012. Something like 1st of every three months, So I add 3 months the month comes out to be Feb 2013. But I want to set Day 1st Feb 2013. I am unable to do it. Kindly help.
You can set whatever day of month by add month.
DateTime todayDate = DateTime.Now;
DateTime after3MonthDate = todayDate.AddMonths(3);
//Set First Day of Month
after3MonthDate = new DateTime(after3MonthDate.Year, after3MonthDate.Month, 1);
This code can be used for existing date time variable to set the day part to the first day of the month:
if(myDate.Day > 1)
{
myDate = myDate.AddDays(-(myDate.Day - 1));
}
Try this:
// Here is the simple wrapper method to get the first day of the month:
public DateTime FirstDayOfMonthFromDateTime(DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, 1);
}
// Set the due date...
DueDate.Text = (FirstDayOfMonthFromDateTime(DateTime.Parse(StartDate.Text).AddMonths(N))).ToShortDateString();
You can also modify the wrapper method to get any day of the month:
public DateTime DayOfMonthFromDateTime(DateTime dateTime, int day)
{
return new DateTime(dateTime.Year, dateTime.Month, day);
}

Calculate DateTime Weeks into Rows

I am currently writing a small calendar in ASP.Net C#. Currently to produce the rows of the weeks I do the following for loop:
var iWeeks = 6;
for (int w = 0; w < iWeeks; w++) {
This works fine, however, some month will only have 5 weeks and in some rare cases, 4.
How can I calculate the number of rows that will be required for a particular month?
This is an example of what I am creating:
As you can see for the above month, there are only 5 rows required, however. Take the this month (August 2008) which started on a Saturday and ends on a Monday on the 6th Week/Row.
Image found on google
This is an example of what I am creating:
As you can see for the above month, there are only 5 rows required, however. Take the this month (August 2008) which started on a Saturday and ends on a Monday on the 6th Week/Row.
Image found on google
Here is the method that does it:
public int GetWeekRows(int year, int month)
{
DateTime firstDayOfMonth = new DateTime(year, month, 1);
DateTime lastDayOfMonth = new DateTime(year, month, 1).AddMonths(1).AddDays(-1);
System.Globalization.Calendar calendar = System.Threading.Thread.CurrentThread.CurrentCulture.Calendar;
int lastWeek = calendar.GetWeekOfYear(lastDayOfMonth, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
int firstWeek = calendar.GetWeekOfYear(firstDayOfMonth, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
return lastWeek - firstWeek + 1;
}
You can customize the calendar week rule by modifying the System.Globalization.CalendarWeekRule.FirstFourDayWeek part. I hope the code is self explanatory.
Well, it depends on the culture you're using, but let's assume you can use Thread.CurrentThread.CurrentCulture, then the code to get the week of today would be:
Culture culture = Thread.CurrentThread.CurrentCulture;
Calendar cal = culture.Calendar;
Int32 week = cal.GetWeekOfYear(DateTime.Today,
culture.DateTimeFormat.CalendarWeekRule,
culture.DateTimeFormat.FirstDayOfWeek);
How about checking which week the first and last days will be in?
you can get the days of a month by using DateTime.DaysInMonth(int WhichYear,int WhichMonth);
The months in the Julian / Gregorian calendar have the same number of days each year, except February who can have 28 or 29 days depending on the leapness of the year. You can find the number of days in the Description section at http://en.wikipedia.org/wiki/Gregorian_calendar.
As #darkdog mentioned you have DateTime.DaysInMonth. Just do this:
var days = DateTime.DaysInMonth(year, month) +
WhatDayOfWeekTheMonthStarts(year, month);
int rows = (days / 7);
if (0 < days % 7)
{
++rows;
}
Take into consideration the fact that for globalization / localization purposes, some parts of the world use different calendars / methods of organization of the year.
The problem isn't the number of days in the month, it's how many weeks it spans over.
February in a non-leap year will have 28 days, and if the first day of the month is a monday, february will span exactly 4 week numbers.
However, if the first day of the month is a tuesday, or any other day of the week, february will span 5 week numbers.
A 31 day month can span 5 or 6 weeks the same way. If the month starts on a monday, the 31 days gives you 5 week numbers. If the month starts on saturday or sunday, it will span 6 week numbers.
So the right way to obtain this number is to find the week number of the first and last days of the month.
Edit #1: Here's how to calculate the number of weeks a given month spans:
Edit #2: Fixed bugs in code
public static Int32 GetWeekForDateCurrentCulture(DateTime dt)
{
CultureInfo culture = Thread.CurrentThread.CurrentCulture;
Calendar cal = culture.Calendar;
return cal.GetWeekOfYear(dt,
culture.DateTimeFormat.CalendarWeekRule,
culture.DateTimeFormat.FirstDayOfWeek);
}
public static Int32 GetWeekSpanCountForMonth(DateTime dt)
{
DateTime firstDayInMonth = new DateTime(dt.Year, dt.Month, 1);
DateTime lastDayInMonth = firstDayInMonth.AddMonths(1).AddDays(-1);
return
GetWeekForDateCurrentCulture(lastDayInMonth)
- GetWeekForDateCurrentCulture(firstDayInMonth)
+ 1;
}
Try this,
DateTime.DaysInMonth
First Find out which weekday the first day of the month is in. Just new up a datetime with the first day, always 1, and the year and month in question, there is a day of week property on it.
Then from here, you can use the number of days in the month, DateTime.DaysInMonth, in order to determine how many weeks when you divide by seven and then add the number of days from 1 that your first day falls on. For instance,
public static int RowsForMonth(int month, int year)
{
DateTime first = new DateTime(year, month, 1);
//number of days pushed beyond monday this one sits
int offset = ((int)first.DayOfWeek) - 1;
int actualdays = DateTime.DaysInMonth(month, year) + offset;
decimal rows = (actualdays / 7);
if ((rows - ((int)rows)) > .1)
{
rows++;
}
return rows;
}
Check Calendar.GetWeekOfYear. It should do the trick.
There is a problem with it, it does not follow the 4 day rule by ISO 8601, but otherwise it is neat.

Categories

Resources