how to get the days for particular month and year - c#

I have a method which passes two parameters Month and year
i will call this Method like this : MonthDates(January,2010)
public static string MonthDates(string MonthName,string YearName)
{
return days;
}
How to get the days for particular month and year?

do you mean the number of days in a month?
System.DateTime.DaysInMonth(int year, int month)

If you want all days as a collection of DateTime:
public static IEnumerable<DateTime> daysInMonth(int year, int month)
{
DateTime day = new DateTime(year, month, 1);
while (day.Month == month)
{
yield return day;
day = day.AddDays(1);
}
}
The use is:
IEnumerable<DateTime> days = daysInMonth(2010, 07);

System.DateTime.Now.Month
System.DateTime.Now.Year
System.DateTime.Now.Day
And so on.........You have lots of things you can get from DateTime.Now

instead of string try to declare an enum like the following
public enum Month
{
January = 1,
February,
March,
.... so on
}
then pass it to the function of yours and use the followings in your function
return System.DateTime.DaysInMonth(year, month);
Instead of string try to use integer, as it will reduce the overhead of parsing strings.

Related

How could I get months week number based on year week number (i.e week 33)

I'm wondering how can I calculate what is the week of the month based on the ordinal number of the week of the year. For example I'm dealing with week 33, I should know that's Week 2 in august.
I allready calculated months but now I'm dealing with weeks.
I allready have a solution, but it seems dirty to me..
Here's the code:
var data = query.GroupBy(x => CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(x.CreatedDate ?? DateTime.UtcNow, CalendarWeekRule.FirstDay, DayOfWeek.Monday))
.Select(article => new ArticleSimpleObject
{
Week = GetWeekNumberOfMonth(article.FirstOrDefault().CreatedDate.Value),
Amount = article.Sum(x => x.Amount),
Month = article.FirstOrDefault().CreatedDate.Value.Month
});
And here's the method which I used to get week numbers:
private static int GetWeekNumberOfMonth(DateTime date)
{
date = date.Date;
DateTime firstMonthDay = new DateTime(date.Year, date.Month, 1);
DateTime firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
if (firstMonthMonday > date)
{
firstMonthDay = firstMonthDay.AddMonths(-1);
firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
}
return (date - firstMonthMonday).Days / 7 + 1;
}
As I wrote guys, this solutions works,
but I personally don't like it, I guess there is more elegant solution, and that's why I posted this question to help to myself and to future readers if some experienced person helps us to solve this :)
Maybe this could be solved based on Calendar class https://learn.microsoft.com/en-us/dotnet/api/system.globalization.calendar?view=netframework-4.8
I've tried some variant but I was not even close to solve it..
Thanks guys
Cheers
One approach is to subtract the week of the year of the 1st day of the month of the date from the week of the year of the date. Like so:
void Main()
{
Console.WriteLine(DateTime.Now.GetWeekOfMonth());
}
public static class MyDateTimeExtensions
{
private static GregorianCalendar _calendar = new GregorianCalendar();
public static int GetWeekOfMonth(this DateTime date)
{
return
date.GetWeekOfYear()
- new DateTime(date.Year, date.Month, 1).GetWeekOfYear()
+ 1;
}
private static int GetWeekOfYear(this DateTime date)
{
return _calendar.GetWeekOfYear(
date,
CalendarWeekRule.FirstDay,
DayOfWeek.Sunday);
}
}
This outputs 4 for the current date: Sept. 23rd, 2019.
You can write a couple of general extensions to compute this a little bit simpler.
First, you need the first date of the week starting on a particular day of week for a date:
public static DateTime FirstDateOfWeekStarting(this DateTime aDate, DayOfWeek dow) => aDate.Date.AddDays((int)dow - (int)aDate.DayOfWeek);
Then, you can easily convert the day of month of that first date to the Week Number in the month:
public static int WeekStartingDOWNumOfMonth(this DateTime aDate, DayOfWeek dow) => (aDate.FirstDateOfWeekStarting(dow).Day-1) / 7 + 1;
And, for your specific case of weeks beginning with Monday,
public static int WeekStartingMonNumOfMonth(this DateTime aDate) => aDate.WeekStartingDOWNumOfMonth(DayOfWeek.Monday);

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);

How to get 3 days back of current date and should not be weekends

How can I get 3 days back of current date and should not fall on weekends (Sat/Sun)
Let's say if date i select date as 03/28/2017. It should display date as 03/23/2017. It should not take sat/sun.
dto.ProcessEndDate.AddDays(-3);
This code assumes that if new date falls on a weekend, it will instead return the Friday before.
public static DateTime GetDateExcludeWeekends(DateTime date, int index)
{
var newDate = date.AddDays(-index);
if(newDate.DayOfWeek == DayOfWeek.Sunday)
{
return newDate.AddDays(-2);
}
if(newDate.DayOfWeek == DayOfWeek.Saturday)
{
return newDate.AddDays(-1);
}
return DateTime.Now;
}
You can tweak the logic, but the main thing is to look at the DayOfWeek enum property of the DateTime class.

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();
}

How do you do end-of-week rounding on a date field in C# (without using LINQ)?

I have a weird date rounding problem that hopefully someone can solve. My client uses a work week that runs from Monday through Sunday. Sunday's date is considered the end of the week, and is used to identify all records entered in a particular week (so anything entered last week would have a WEEKDATE value of '10/26/2008', which is Sunday's date).
One little twist is that users enter records for the previous week up until 11 AM on the Monday of the current week.
So I need a function that starts with DateTime.Now and returns the week-ending date (no time part) according to the rules above. Thanks for your help. I have a solution that works, but I'm too embarassed to post it.
Oh, and I can't use LINQ.
public DateTime WeekNum(DateTime now)
{
DateTime NewNow = now.AddHours(-11).AddDays(6);
return (NewNow.AddDays(- (int) NewNow.DayOfWeek).Date);
}
public void Code(params string[] args)
{
Console.WriteLine(WeekNum(DateTime.Now));
Console.WriteLine(WeekNum(new DateTime(2008,10,27, 10, 00, 00)));
Console.WriteLine(WeekNum(new DateTime(2008,10,27, 12, 00, 00)));
Console.WriteLine(WeekNum(new DateTime(2008,10,28)));
Console.WriteLine(WeekNum(new DateTime(2008,10,25)));
}
You may hard-code DateTime.Now instead of passing a DateTime object. It just made testing easier this way.
This passes for me as well:
[Test]
public void Test()
{
DateTime sunday = DateTime.Parse("10/26/2008");
DateTime nextSunday = DateTime.Parse("11/2/2008");
Assert.AreEqual(sunday, GetSunday(DateTime.Parse("10/21/2008")));
Assert.AreEqual(sunday, GetSunday(DateTime.Parse("10/22/2008")));
Assert.AreEqual(sunday, GetSunday(DateTime.Parse("10/23/2008")));
Assert.AreEqual(sunday, GetSunday(DateTime.Parse("10/24/2008")));
Assert.AreEqual(sunday, GetSunday(DateTime.Parse("10/25/2008")));
Assert.AreEqual(sunday, GetSunday(DateTime.Parse("10/26/2008")));
Assert.AreEqual(sunday, GetSunday(DateTime.Parse("10/27/2008 10:59 AM")));
Assert.AreEqual(nextSunday, GetSunday(DateTime.Parse("10/27/2008 11:00 AM")));
}
private DateTime GetSunday(DateTime date)
{
if (date.DayOfWeek == DayOfWeek.Monday && date.Hour < 11)
return date.Date.AddDays(-1);
while (date.DayOfWeek != DayOfWeek.Sunday)
date = date.AddDays(1);
return date.Date;
}
DateTime GetMidnightFollowingSunday()
{
DateTime now = DateTime.Now;
return now.AddDays(7 - (int)now.DayOfWeek).Date;
}
If you need to start the new week after 11AM on Monday morning just subtract 11 hours from now but then it probably makes sense to name the method something else.
DateTime GetRecordDate()
{
DateTime nowMinusOffset = DateTime.Now.AddHours(-11);
return nowMinusOffset.AddDays(7-(int)nowMinusOffset.DayOfWeek).Date;
}
I've used these extensions with great success:
http://www.codeplex.com/DateTimeExtensions

Categories

Resources