Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am working on a weather application and I want that when the user input "Tuesday" and the present day is Wednesday, it will give me the weather of the coming Tuesday instead.
Any help please?
There are many ways to get "next Tuesday" but the exact solution depends on the answer to this question:
If today is Tuesday, and the user types in Tuesday, do you want today, or next week?
If the answer is "Today", then the following two solutions will work:
public static DateTime NextDateByDayOfWeek1(DayOfWeek dow)
{
var daysUntil = ((dow - DateTime.Today.DayOfWeek) + 7) % 7;
return DateTime.Today.AddDays(daysUntil);
}
public static DateTime NextDateByDayOfWeek2(DayOfWeek dow)
{
var date = DateTime.Today;
while (date.DayOfWeek != dow)
date = date.AddDays(1);
return date;
}
If the answer is "next week", you should simply add 1 day to the date you use in the methods:
public static DateTime NextDateByDayOfWeek1(DayOfWeek dow)
{
var daysUntil = ((dow - DateTime.Today.AddDays(1).DayOfWeek) + 7) % 7;
return DateTime.Today.AddDays(1 + daysUntil);
}
public static DateTime NextDateByDayOfWeek2(DayOfWeek dow)
{
var date = DateTime.Today.AddDays(1);
while (date.DayOfWeek != dow)
date = date.AddDays(1);
return date;
}
You can even generalize them:
public static DateTime NextDateByDayOfWeek1(DateTime startDate, DayOfWeek dow)
{
var daysUntil = ((dow - startDate.DayOfWeek) + 7) % 7;
return startDate.AddDays(daysUntil);
}
public static DateTime NextDateByDayOfWeek2(DateTime startDate, DayOfWeek dow)
{
var date = startDate;
while (date.DayOfWeek != dow)
date = date.AddDays(1);
return date;
}
The startDate will be returned if it is already of the correct day of the week. To get "next week's date", simply use DateTime.Today.AddDays(1) when calling it, otherwise use DateTime.Today.
Why two solutions?
Because the "worst case scenario" for the loop-based solution is 6 iterations, whereas the one using the remainder operator might need some documentation to be understood by people who reads this code. Pros and cons.
It depends on how the day is selected, but you should be able to use DateTime.DayOfWeek
var datetimeNow = DateTime.Now; // Wednesday
var selectedDay = Datetime.Now.AddDays(-1); //Tuesday
if(datetimeNow.DayOfWeek < selectedDay.DayOfWeek)
selectedDay = selectedDay.AddDays(7); // Will then be the coming tuesday
Hope it makes sense
DayOfWeek is an int based enum, (sunday=0 - saturday = 7) so it can be used to calculate the days until your desired day.
var input = DayOfWeek.Monday;
DateTime today = DateTime.Today;
int days = input - today.DayOfWeek;
days = days < 0 ? days+7 : days; // fix it if we past that day already.
var newDate = today.AddDays(days);
Related
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);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I've written this so far but I can seem to get it so the Operator command right. I want to write it so when it is between Monday and Friday Excecute said code.
DayOfWeek day = DateTime.Now.DayOfWeek;
TimeSpan now = DateTime.Now.TimeOfDay;
string FromDate = string.Empty;
TimeSpan FromTime = new TimeSpan();
TimeSpan ToTime = new TimeSpan();
foreach (var key in applicationSettings.AllKeys)
{
if (key == "FromDate")
{
FromDate = applicationSettings[key];
}
if ((day >= FromDate) && (now > FromTime) && (now < ToTime))
{
// execute code here
}
I cannot get the FromDate to work properly. FromTime, ToTime is 8:00 AM and 17:00.
To answer the "between Monday and Friday" part of your question:
The DayOfWeek Is an enum representation of the week Starting at Sunday to Saturday.
You can store it in your config, the index may be the easiest way to represent those day:
<add key="FromDay" value="1" /> <!--Monday-->
<add key="ToDay" value="5" /> <!--Friday-->
Now a simple cast and comparaison will give you result you need:
var confRead = new System.Configuration.AppSettingsReader();
var fromDay= (int)confRead.GetValue("FromDay", typeof(int));
var toDay = (int)confRead.GetValue("ToDay", typeof(int));
var result = IsValidDay(DateTime.Now, fromDay, toDay);
private bool IsValidDay(DateTime day, int fromDay = 1, int toDay = 5)
{
var testDay = (int)day.DayOfWeek;
return (fromDay > testDay && testDay > toDay);
}
You can now apply the same logic to find if we are between 08:00 and 17:00. Using TimeSpan and 'TimeOfDay'
This can be considered as a way. Might not be really efficient. But can be considered.
You can probably add a new variable and convert your FromDate to enum and save it there.
DayOfWeek FromDateEnum;
if (key == "FromDate")
{
FromDate = applicationSettings[key];
Enum.TryParse<DayOfWeek>(FromDate, out FromDateEnum);
}
and change your if condition to use enum rather than string
if ((day >= FromDateEnum ) && (now > FromTime) && (now < ToTime))
{
// execute code here
}
and in addition to that you can easily manage using FromDateEnum to compare with DayOfWeek Enum values.
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Getting specific days in a month
I've touched on this problem once before, in How to find the 3rd Friday in a month with C#? But since I did not explain my problem well then, I must try again:
My goal here is simple: upon the press of a button (referred to here as "Button1"), I must determine whether today's date is prior to either the first, or the third Wednesday of the month. If this is the case, I must then set the text of a label (referred to here as "lblDate") to the date of whichever of these future Wednesdays is nearest to the current date.
So far, I've written this:
protected void Button1_Click(object sender, EventArgs e)
{
DateTime Now = DateTime.Today;
DateTime TempDate = new DateTime(Now.Year, Now.Month, 1);
if (TempDate.DayOfWeek != DayOfWeek.Wednesday)
{
TempDate = TempDate.AddDays(1);
string date = TempDate.ToString();
lblDate.Text = date;
}
if (TempDate == TempDate.AddDays(1))
{
TempDate = TempDate.AddDays(14);
string date = TempDate.ToString();
lblDate.Text = date;
}
}
As you can see, something is missing. I would greatly appreciate any assistance in filling that in...
You could also try it like this:
protected DateTime getFirstWednesdayOfMonth(DateTime seedDate)
{
DateTime wed1 = new DateTime(seedDate.Year, seedDate.Month, 1); //1st Wednesday can start on the 1st of the month
while (wed1.DayOfWeek != DayOfWeek.Wednesday)
{
wed1 = wed1.AddDays(1);
}
return wed1;
}
protected DateTime getThirdWednesdayOfMonth(DateTime seedDate)
{
DateTime wed3 = new DateTime(seedDate.Year, seedDate.Month, 15); //3rd Wednesday cannot start prior to the 15th of the month
while (wed3.DayOfWeek != DayOfWeek.Wednesday)
{
wed3 = wed3.AddDays(1);
}
return wed3;
}
protected void Button1_Click(object sender, EventArgs e)
{
DateTime Now = DateTime.Today;
DateTime wed1 = getFirstWednesdayOfMonth(Now);
DateTime wed3 = getThirdWednesdayOfMonth(Now);
if (Now < wed1)
{
lblDate.Text = wed1.ToString();
}
else if (Now < wed3)
{
lblDate.Text = wed3.ToString();
}
}
Well I'm not entirely sure this will answer your question but it might get you on the right track. You can figure out the day of the week from the DateTime feature. Just use something similar to:
DateTime dateValue = new DateTime(2008, 6, 11);
Console.WriteLine((int) dateValue.DayOfWeek); // Displays 3
Use that in conjunction with the actual date say something like:
if((int) dateValue.DayOfWeek == 3) //which is Wednesday
if(date < 7 && date > 1)
week == 1st Weds of month
else(date < 21 && date > 14)
week == 3rd Weds of month
That's not exact code obviously but perhaps something along those lines would help out a little. And you will have to adjust the parameters a bit in order to adjust for the 1st not falling exactly on a monday. Since there is only seven days in a week and even if the first falls on a tuesday it just fall within the range of 1 and 7, likewise for 14 and 21. But just play around with that and you should figure the answer out soon enough.
I am wondering if i can get the date of every alternate friday starting with 13th of April, 2012 to give it as a parameter to a stored procedure using c#, asp.net?
It should also be most recently passed date. Thank you!
Just set a DateTime with the date you want to start at, and then keep adding 14 days:
So to get every other Friday after 4/13 until the end of the year:
DateTime dt = new DateTime(2012, 04, 13);
while (dt.Year == 2012)
{
Console.WriteLine(dt.ToString());
dt = dt.AddDays(14);
}
More info after comment:
If you want the most recent alternate Friday since 2012/04/13, you can compute the number of days between now and 2012/04/13, take the remainder of that divided by 14, and subtract that many days from today's date:
DateTime baseDate = new DateTime(2012, 04, 13);
DateTime today = DateTime.Today;
int days = (int)(today - baseDate).TotalDays;
int rem = days % 14;
DateTime mostRecentAlternateFriday = today.AddDays(-rem);
You can easily make a generator method that would give you the set of fridays:
public IEnumerable<DateTime> GetAlternatingFridaysStartingFrom(DateTime startDate)
{
DateTime tempDate = new DateTime(startDate.year, startDate.Month, startDate.Day);
if(tempDate.DayOfWeek != DayOfWeek.Friday)
{
// Math may be off, do some testing
tempDate = tempDate.AddDays((7 - ((int)DayOfWeek.Friday - (int)tempDate.DayOfWeek) % 7);
}
while(true)
{
yield return tempDate;
tempDate = tempDate.AddDays(14);
}
}
Then, simply use some LINQ to determine how much you want:
var numberOfFridays = GetAlternatingFridaysStartingFrom(DateTime.Today).Take(10);
Why do you need a stored proc?
If you have a date that is Friday, why not just use AddDays(14) in a loop?
If you want to find the nearest Friday from a start date, just use this:
while(date.DayOfWeek != DayOfWeek.Friday)
{
date.AddDays(1);
}
Then use the 14 day loop to get every other Friday.
You can create simple method that will enumerate them like so:
public static IEnumerable<DateTime> GetAlternatingWeekDay(DateTime startingDate)
{
for (int i = 1; ; i++)
{
yield return startingDate.AddDays(14*i);
}
}
Which you can call like this:
DateTime startingDate = DateTime.Parse("2012-04-13");
foreach (var date in GetAlternatingWeekDay(startingDate).Take(10))
{
Console.WriteLine(date.ToString("R"));
}
Alternately, if you need to know the date for a given number of weeks out, you could use code like this:
DateTime date = DateTime.Parse("2012-04-13").AddDays(7 * numberOfWeeks);
This question already has answers here:
How can I get the DateTime for the start of the week?
(34 answers)
Closed 8 years ago.
I was wondering if you guys know how to get the date of currents week's monday based on todays date?
i.e 2009-11-03 passed in and 2009-11-02 gets returned back
/M
This is what i use (probably not internationalised):
DateTime input = //...
int delta = DayOfWeek.Monday - input.DayOfWeek;
DateTime monday = input.AddDays(delta);
The Pondium answer can search Forward in some case. If you want only Backward search I think it should be:
DateTime input = //...
int delta = DayOfWeek.Monday - input.DayOfWeek;
if(delta > 0)
delta -= 7;
DateTime monday = input.AddDays(delta);
Something like this would work
DateTime dt = DateTime.Now;
while(dt.DayOfWeek != DayOfWeek.Monday) dt = dt.AddDays(-1);
I'm sure there is a nicer way tho :)
public static class DateTimeExtension
{
public static DateTime GetFirstDayOfWeek(this DateTime date)
{
var firstDayOfWeek = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
while (date.DayOfWeek != firstDayOfWeek)
{
date = date.AddDays(-1);
}
return date;
}
}
International here. I think as extension it can be more useful.
What about:
CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek
Why don't use native solution?
var now = System.DateTime.Now;
var result = now.AddDays(-((now.DayOfWeek - System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek + 7) % 7)).Date;
Probably will return you with Monday. Unless you are using a culture where Monday is not the first day of the week.
Try this:
public DateTime FirstDayOfWeek(DateTime date)
{
var candidateDate=date;
while(candidateDate.DayOfWeek!=DayOfWeek.Monday) {
candidateDate=candidateDate.AddDays(-1);
}
return candidateDate;
}
EDIT for completeness: overload for today's date:
public DateTime FirstDayOfCurrentWeek()
{
return FirstDayOfWeek(DateTime.Today);
}