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();
}
Related
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.
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);
I'm using the following to get the current week number:
var weekNo = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(DateTime.UtcNow,
CalendarWeekRule.FirstFullWeek,
DayOfWeek.Sunday);
And I want to return the DateTime representing the first day of the nth week after today.
e.g. when n = 2, I would want the DateTime representing the Sunday after next.
Is there a way I can do this in C#?
You could use:
DateTime sundayInFuture = DateTime.Today.AddDays((n - 1) * 7 + (7 - (int)DateTime.Today.DayOfWeek));
That should work (though I've not got access to anything to test it!).
Edit: Thanks to the comments.
This should work:
int n = 2;
DateTime today = DateTime.Today;
int daysToNextSunday = (7 - today.DayOfWeek - DayOfWeek.Sunday) ;
DateTime nthSunday = today.AddDays((n - 1) * 7 + daysToNextSunday);
Could you add the number of days from now until Sunday, and then add (n-1)*7 more days?
Please note, that Calendar.GetWeekOfYear is not ISO 8601 conform.
Here a sample Using the Week class of the Time Period Library for .NET:
// ----------------------------------------------------------------------
public DateTime GetStartOfWeek( DateTime moment, int offset )
{
return new Week( new Week( moment ).WeekOfYear + Math.Abs( offset ) ).FirstDayOfWeek;
} // GetStartOfWeek
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.
How can I convert a number between 1 and 7 into a DateTime object in C# which represents the day of the week? The numbers are coming from a XML file which I am parsing. I am retrieving each instance of a field containing a number between 1 and 7 which represents a day of the week between Sunday and Saturday.
I would assume casting to a DayOfWeek object would give you a day of the week
DayOfWeek day = (DayOfWeek)myInt;
As far as a DateTime object goes, the object represents a specific day, not necessarily a random day of the week. You may try adding a # of days to a specific date if this is what you're trying to achieve.
http://msdn.microsoft.com/en-us/library/system.dayofweek.aspx
In order to get a DateTime, you'd need a specific range of dates that you want the weekday to fall under (since a DateTime is a specific date and time, and a weekday isn't).
There is a DayOfWeek enumeration (whose values actually range from 0-6). If all you need is something to represent the day of the week, then you should be able to cast your int to a DayOfWeek like..
DayOfWeek myDay = (DayOfWeek)yourInt;
If you need an actual DateTime, you'll need a start date. You could then do...
DateTime myDate = startDate.AddDays(
(int)startDate.DayOfWeek >= yourInt ?
(int)startDate.DayOfWeek - yourInt :
(int)startDate.DayOfWeek - yourInt + 7);
This will give you a DateTime for the next occuring instance of the day of the week you're describing.
DayOfWeek.Sunday is zero, so you could start with an arbitrary fixed date that you know to be Sunday, and add a value between 0 and 6:
public DateTime GetDayOfWeek(int dayOfWeek)
{
if (dayOfWeek < 0 || dayOfWeek > 6) throw new ArgumentOutOfRangeException(...);
// 4 January 2009 was a Sunday
return new DateTime(2009,1,4).AddDays(dayOfWeek);
}
I'm not sure why you would want this though.
If you only want it to get a localized version of the day of the week as in:
GetDayOfWeek(3).ToString("dddd"); // Gets name of day of week for current culture
an alternative would be to use DateTimeFormatInfo.DayNames or DateTimeFormatInfo.AbbreviatedDayNames for the culture you want.
A DateTime instance represents alway a complete date and cannot only represent a day of the week. If the actual date does not matter, take any monday (assuming 0 represents monday) and just add the number of the day.
Int32 dayOfWeek = 3;
// date represents a thursday since 2009/04/20 is a monday
DateTime date = new DateTime(2009, 04, 20).AddDays(dayOfWeek);
Else I agree with Adam Robinson's answer - if you just want to hold the day of a week, stick with the DayOfWeek enum (zero is sunday) instead of using an integer.