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);
}
Related
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);
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.
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);
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
This question already has answers here:
How do I get the last day of a month?
(16 answers)
Closed 7 years ago.
How can I find the last day of the month in C#?
Another way of doing it:
DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year,
today.Month,
DateTime.DaysInMonth(today.Year,
today.Month));
Something like:
DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1).AddDays(-1);
Which is to say that you get the first day of next month, then subtract a day. The framework code will handle month length, leap years and such things.
public static class DateTimeExtensions
{
public static DateTime LastDayOfMonth(this DateTime date)
{
return date.AddDays(1-(date.Day)).AddMonths(1).AddDays(-1);
}
}
DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)
try this. It will solve your problem.
var lastDayOfMonth = DateTime.DaysInMonth(int.Parse(ddlyear.SelectedValue), int.Parse(ddlmonth.SelectedValue));
DateTime tLastDayMonth = Convert.ToDateTime(lastDayOfMonth.ToString() + "/" + ddlmonth.SelectedValue + "/" + ddlyear.SelectedValue);