Nodatime and days in month - c#

I'm trying to get the number of days in a month. So I have the following
var fromdate = LocalDateTime.FromDateTime(DateTime.Now).Date;
Now I just need the number of days in that LocalDateTime variable that I just created. It seems like I could enter:
var m = fromdate.Calendar.GetDaysInMonth(year, month)
But I already know the year/month in fromdate. What is it that I'm doing wrong?

You can use DateTime's GetDaysInMonth method:
int days = DateTime.DaysInMonth(year, month);

Related

C# - Get the first day and last day of the week knowing the week number, month number and year

so the problem is this: I managed to get the number of weeks that make up a month (for example: May 2022 is made up of 6 weeks counting from day 1 to day 31 without exception). So having the number of weeks that make up a month I need to know, knowing also the number of the month and the year, which will be the first and last day of the selected week.
I tried to do some research but I only find solutions that use the Calendar.GetWeekOfYear method but, as I said before, I have the week number for the single month not the total for the year.
I hope you can help me. Thanks in advance.
If I understood correctly it should look something like this
var week = 2;
var month = 5;
var year = 2022;
var firstDayOfMonth = new DateTime(year, month, 1);
var dayOfWeek = firstDayOfMonth.DayOfWeek;
var diffToMonday = (7 + (dayOfWeek - DayOfWeek.Monday)) % 7;
var firstMonday = firstDayOfMonth.AddDays(-diffToMonday);
var requestedMonday = firstMonday.AddDays(7 * (week - 1));
var requestedSunday = firstMonday.AddDays(7 * week - 1);

Getting date using day of the week

I have problem in finding the date using day of the week.
For example : i have past date lets say,
Date date= Convert.TodateTime("01/08/2013");
08th Jan 2013 th Day of the week is Tuesday.
Now i want current week's tuesday's date. How i can do it.
Note : The past date is dynamic. It will change in every loop.
You can use the enumeration DayOfWeek
The DayOfWeek enumeration represents the day of the week in calendars
that have seven days per week. The value of the constants in this
enumeration ranges from DayOfWeek.Sunday to DayOfWeek.Saturday. If
cast to an integer, its value ranges from zero (which indicates
DayOfWeek.Sunday) to six (which indicates DayOfWeek.Saturday).
We can use the conversion to integer to calculate the difference from the current date of the same week day
DateTime dtOld = new DateTime(2013,1,8);
int num = (int)dtOld.DayOfWeek;
int num2 = (int)DateTime.Today.DayOfWeek;
DateTime result = DateTime.Today.AddDays(num - num2);
This also seems appropriate to create an extension method
public static class DateTimeExtensions
{
public static DateTime EquivalentWeekDay(this DateTime dtOld)
{
int num = (int)dtOld.DayOfWeek;
int num2 = (int)DateTime.Today.DayOfWeek;
return DateTime.Today.AddDays(num - num2);
}
}
and now you could call it with
DateTime weekDay = Convert.ToDateTime("01/08/2013").EquivalentWeekDay();
I may be a bit late to the party, but my solution is very similar:
DateTime.Today.AddDays(-(int)(DateTime.Today.DayOfWeek - DayOfWeek.Tuesday));
This will get the Tuesday of the current week, where finding Tuesday is the primary goal (I may have misunderstood the question).
You can use this....
public static void Main()
{
//current date
DateTime dt = DateTime.UtcNow.AddHours(6);
//you can use it custom date
var cmYear = new DateTime(dt.Year, dt.Month, dt.Day);
//here 2 is the day value of the week in a date
var customDateWeek = cmYear.AddDays(-2);
Console.WriteLine(dt);
Console.WriteLine(cmYear);
Console.WriteLine("Date: " + customDateWeek);
Console.WriteLine();
Console.ReadKey();
}

C# Add TimeSpan to DateTime by considering BusinessDays

I have a collection of dates that are business days and I have a Start Date. When I add a TimeSpan to the Start Date DateTime I have to ensure that when adding the days in TimeSpan, I skip over holidays. Any suggestions on how I can do this?
You add the timespan as it is. When that is done, you iterate search for dates in your collection that falls between the original date and the new date. For each time you encounter for each hit you add another day to the new date, and repeat until you are through your collection of dates. This can be optimized if your datecollection is sorted.
You need to take into account how many non-business days there are in any added date range.
In a 20 day range, there may be 6 non-business days.
You can't just add this number of days to the last day because the new date range may contain non-business days too. You have to add the days, and then figure out how many of those days you've added are also holidays:
Here's some non-tested pcode
Add Timespan to date (DateIn,timespan)
finalDateTime = (fromDate + timespan)
fromDate = DateIn.date
toDate = finalDateTime.date
repeat
iDays = GetHolidaysBetween (fromDate, toDate)
finalDateTime = (finalDateTime + iDays)
fromDate = (toDate+1)
toDate = (toDate+iDays)
until (iDays=0)
return finalDateTime
end_function
What about something like this?
public DateTime AddBusinessDays(List<DateTime> businessDays, DateTime startDate, TimeSpan span)
{
// Add the initial timespan
DateTime endDate = startDate.Add(span);
// Calculate the number of holidays by taking off the number of business days during the period
int noOfHolidays = span.Days - businessDays.Where(d => d >= startDate && d <= endDate).Count();
// Add the no. of holidays found
endDate.AddDays(noOfHolidays);
// Skip the end date if it lands on a holiday
while (businessDays.Contains(endDate))
endDate = endDate.AddDays(1);
return endDate;
}

How to subtract a year from the datetime?

How to subtract a year from current datetime using c#?
var myDate = DateTime.Now;
var newDate = myDate.AddYears(-1);
DateTime oneYearAgoToday = DateTime.Now.AddYears(-1);
Subtracting a week:
DateTime weekago = DateTime.Now.AddDays(-7);
It might be worth noting that the accepted answer may adjust the date by either 365 days or 366 days due to leap years (it gets the date for the same day of the month one year ago, with the exception of 29th February where it returns 28th February).
In the vast majority of cases this is exactly what you want however if you are treating a year as a fixed unit of time (e.g. the Julian year) then you would need to subtract from either days;
var oneFullJulianYearAgo = DateTime.Now.AddDays(-365.25);
or seconds;
var oneFullJulianYearAgo = DateTime.Now.AddSeconds(-31557600);

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