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 6 years ago.
Improve this question
I have this code written into my main class (C#) for the Birthday reminders. It used to work but now it doesn't. I haven't changed the code at all. What the problem could be?
/// <summary>
/// Find all members that have birthdays occurring this week
/// </summary>
/// <returns>Returns an ArrayList containing members</returns>
public ArrayList BirthdaysThisWeek()
{
ArrayList members = new ArrayList();
DateTime today = DateTime.Today;
//Work out how many days to add or to take away to get us to Monday
int delta = DayOfWeek.Monday - today.DayOfWeek;
//Change the date to point to Monday
DateTime monday = today.AddDays(delta);
//Make this date point to Sunday
DateTime sunday = monday.AddDays(6);
foreach (Member member in allMembers)
{
DateTime dob = member.DateOfBirth.Date;
//Check to see if a member's birthdate is between Monday and Sunday
if(dob >= monday.Date && dob <= sunday.Date)
{
//Add member to members ArrayList
members.Add(member);
}
}
//Return all members that have a birthday this week if none were found return an empty ArrayList
return members;
}
Your condition not work because you compare year, month, and day of Birthday with dates of actual week. I changed my answer after the remark of CodeCaster , because DayOfYear don't work with birthdays after February 28th in leap years, you can solve this by initialize dob DateTime like this :
int actuelYear = member.DateOfBirth.Month == monday.Month ? monday.Year : sunday.Year;
DateTime dob = new DateTime(actuelYear, member.DateOfBirth.Month, member.DateOfBirth.Day);
if (dob.Date >= monday.Date && dob.Date <= sunday.Date)
{
members.Add(member);
}
Unless they were born this week, I dont see how this will work.
You need to disregard the Year in which they were born.
public static bool IsBirthDayInRange(DateTime birthday, DateTime start, DateTime end)
{
DateTime temp = birthday.AddYears(start.Year - birthday.Year);
if (temp < start) temp = temp.AddYears(1);
return birthday <= end && temp >= start && temp <= end;
}
Ref: https://stackoverflow.com/a/2554881/495455
So you need to change your code to this:
public ArrayList BirthdaysThisWeek()
{
ArrayList members = new ArrayList();
DateTime today = DateTime.Today;
int delta = DayOfWeek.Monday - today.DayOfWeek;
DateTime monday = today.AddDays(delta);
DateTime sunday = monday.AddDays(6);
foreach (Member member in allMembers)
{
DateTime dob = member.DateOfBirth.Date;
//Check to see if a member's birthdate is between Monday and Sunday
if (IsBirthDayInRange(dob, monday, sunday)
{
//Add member to members ArrayList
members.Add(member);
}
}
return members;
}
Related
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);
}
I have something odd requirement. I have Current Date and List of Week Days. And I want next all possible date till the target date.
For i.e. Today, its 22-04-2014 And Tuesday. Target date is 15-05-2014I have 2 week days, Monday and Thursday. So code should find near by Week Day, which will be Thursday here. So It should return date of Thursday which is 24-04-2014. Now, next turn is of Monday which comes from List. So now, It should return date of Monday which is 28-04-2014.
It should keep repeating till the target date.
So, final result will be
24-04-2014,
28-04-2014,
1-05-2014,
5-05-2014,
8-05-2014,
12-05-2014
Please help me to get this type of result. Here, Monday and Thursday is not fixed. It can be any Day and any number of Day.
Update : Link to the working example - Example
You can try this code, i have tested it and working correctly
private List<DateTime> ProcessDate(DateTime dtStartDate, DateTime targetDate)
{
DateTime dtLoop = dtStartDate;
//dtRequiredDates to hold required dates
List<DateTime> dtRequiredDates = new List<DateTime>();
for (int i = dtStartDate.DayOfYear; i < targetDate.DayOfYear; i++)
{
if (dtLoop.DayOfWeek == DayOfWeek.Monday || dtLoop.DayOfWeek == DayOfWeek.Thursday)
{
dtRequiredDates.Add(dtLoop);
}
dtLoop = dtLoop.AddDays(1);
}
return dtRequiredDates;
}
You may have to enhance this codes so that it doesn't throw any exception based on the requirement.
UPDATE 2:
You can have another method which will accept the days of week as follows
private List<DateTime> ProcessDate(DateTime dtStartDate, DateTime targetDate, List<DayOfWeek> daysOfWeek)
{
DateTime dtLoop = dtStartDate;
List<DateTime> dtRequiredDates = new List<DateTime>();
for (int i = dtStartDate.DayOfYear; i < targetDate.DayOfYear; i++)
{
foreach (DayOfWeek day in daysOfWeek)
{
if (dtLoop.DayOfWeek == day)
{
dtRequiredDates.Add(dtLoop);
}
}
dtLoop = dtLoop.AddDays(1);
}
return dtRequiredDates;
}
Here is the Example
Hence you can pass any number of week days as you wish.
Hope this helps
You could try something like this:
List<DayOfWeek> listOfDays = new List<DayOfWeek>{DayOfWeek.Monday, DayOfWeek.Thursday};
var end = new DateTime(2014,05,15);
var day = DateTime.Now.Date;
while (day < end)
{
day.AddDays(1); // adds +1 days to "day"
if (listOfDays.Contains(day.DayOfWeek)) Console.WriteLine(day.Date.ToString());
}
(I can't test the code right now, so maybe you need to modify a little ;-)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have to implement a Interface that returns the next weekday date after the date passed in. I need to use this code:
DiaryDate nextWeekday(DiaryDate originalDate);
public DiaryDate(int dayOfMonth, int monthOfYear, int year)
{
DayOfMonth = dayOfMonth;
MonthOfYear = monthOfYear;
Year = year;
}
public int DayOfMonth
{
get;
set;
}
public int MonthOfYear
{
get;
set;
}
public int Year
{
get;
set;
}
Is there a formula for working out which date will be a week day?
I'll just copy from my comment:
Construct a DateTime object and add 1 day while you have Saturday or Sunday. Then take the current day of the week at that time. If it doesn't loop you have your current day, if it does loop it will get you a monday. Or really just check if today is saturday/sunday. If yes: take monday, else take today
var someDate = new DateTime(year, monthOfYear, dayOfMonth).AddDays(1);
if(someDate.DayOfWeek == DayOfWeek.Saturday || someDate.DayOfWeek == DayOfWeek.Sunday) {
return DayOfWeek.Monday;
} else {
return someDate.DayOfWeek;
}
First convert the object into a DateTime to get access to all of the tools available through them:
DateTime date = new DateTime(originalDate.Year, originalDate.Month, originalDate.Day);
Then we can just add a day and then keep adding days while the date is a weekend:
date = date.AddDays(1);
while (date.DayOfWeek == DayOfWeek.Saturday ||
date.DayOfWeek == DayOfWeek.Sunday)
{
date = date.AddDays(1);
}
Then all you need to do is convert it back into your own date object, assuming you can't change your code to use DateTime instead.
This question already has answers here:
How do I loop through a date range?
(17 answers)
Closed 6 years ago.
I have a DateTime StartDate and EndDate.
How can I, irrespective of times, iterate across each Day between those two?
Example: StartDate is 7/20/2010 5:10:32 PM and EndDate is 7/29/2010
1:59:12 AM.
I want to be able to iterate across 7/20, 7/21, 7/22 .. 7/29.
for(DateTime date = StartDate; date.Date <= EndDate.Date; date = date.AddDays(1))
{
...
}
The .Date is to make sure you have that last day, like in the example.
An alternative method that might be more reusable is to write an extension method on DateTime and return an IEnumerable.
For example, you can define a class:
public static class MyExtensions
{
public static IEnumerable EachDay(this DateTime start, DateTime end)
{
// Remove time info from start date (we only care about day).
DateTime currentDay = new DateTime(start.Year, start.Month, start.Day);
while (currentDay <= end)
{
yield return currentDay;
currentDay = currentDay.AddDays(1);
}
}
}
Now in the calling code you can do the following:
DateTime start = DateTime.Now;
DateTime end = start.AddDays(20);
foreach (var day in start.EachDay(end))
{
...
}
Another advantage to this approach is that it makes it trivial to add EachWeek, EachMonth etc. These will then all be accessible on DateTime.
You have to be careful about end-date. For example, in
Example: StartDate is 7/20/2010 5:10:32 PM and EndDate is 7/29/2010 1:59:12 AM.
I want to be able to iterate across 7/20, 7/21, 7/22 .. 7/29.
date < endDate will not include 7/29 ever. When you add 1 day to 7/28 5:10 PM - it becomes 7/29 5:10 PM which is higher than 7/29 2 AM.
If that is not what you want then I'd say you do
for (DateTime date = start.Date; date <= end.Date; date += TimeSpan.FromDays(1))
{
Console.WriteLine(date.ToString());
}
or something to that effect.
The loops of #Yuriy Faktorovich, #healsjnr and #mho will all throw a System.ArgumentOutOfRangeException: The added or subtracted value results in an un-representable DateTime
exception if EndDate == DateTime.MaxValue.
To prevent this, add an extra check at the end of the loop
for(DateTime date = StartDate; date.Date <= EndDate.Date; date = date.AddDays(1))
{
...
if (date.Date == DateTime.MaxValue.Date)
{
break;
}
}
(I would have posted this as a comment to #Yuriy Faktorovich's answer, but I lack reputation)
DateTime date = DateTime.Now;
DateTime endDate = date.AddDays(10);
while (date < endDate)
{
Console.WriteLine(date);
date = date.AddDays(1);
}
How can i learn next wednesday, monday in a week? Forexample Today 06.02.2009 next Monday 09.02.2009 or wednesday 11.02.2009 there is any algorithm?
i need :
which day monday in comingweek?
findDay("Monday")
it must return 09.02.2009
=====================================================
findDay("Tuesday")
it must return 10.02.2009
public static DateTime GetNextDayDate(DayOfWeek day) {
DateTime now = DateTime.Now;
int dayDiff = (int)(now.DayOfWeek - day);
if (dayDiff <= 0) dayDiff += 7;
return now.AddDays(dayDiff);
}
DateTime now = DateTime.Now;
DateTime nextMonday = now.AddDays((int)now.DayOfWeek - (int)DayOfWeek.Monday);
Hum it seems that I answered too quickly. Actually there are more checking to do. Have a look at nobugz or peterchen answers.
I found a simpler solution:
DayOfWeek is an enum, as: Monday=1, Tuesday=2, etc.
So, to get next Monday (from today) you should use:
DateTime.Today.AddDays(8-(int)DateTime.Today.DayOfWeek)
where "8" is next week's Monday(according to the enum-> 1+7).
Replace the 8 for a 10 (i.e. Wednesday, 3+7) and you'll get next week's Wednesday, and so on...
Like Tyalis, but some extra checking is required:
int daysUntilMonday = ((int)DayOfWeek.Monday - (int)today.DayOfWeek;
if (daysUntilMonday <= 0)
daysUntilMonday += 7;
Monday = DateTime.Now.AddDays(daysUntilMonday);
Just iterate a bit:
DateTime baseDate = ...;
DayOfWeek requiredDayOfWeek = ...;
while(baseDate.DayOfWeek != requiredDayOfWeek)
baseDate = baseDate.AddDays(1);
You can also write an extension method if those are available:
static Next(this DateTime date, DayOfWeek requiredDayOfWeek) { ... }
and you'll get pretty syntax: today.Next(DayOfWeek.Saturday).