Determination of the day of the week [closed] - c#

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.

Related

Get number of days in any month without saturday and sunday? [closed]

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 2 years ago.
Improve this question
There is an input string field "Januray 2020". I want to calculate total number of working days in the given month and year.
Can we do this in simple c#?
Since you've not defined what a work day is you can use this function to iterate over all the days in a month according to a predicate:
IEnumerable<DateTime> WorkDaysInMonth(int year, int month, Func<DateTime,bool> isNonWorkDay)
{
var now = new DateTime(year, month, 1);
while(now.Month == month)
{
if(!isNonWorkDay(now))
{
yield return now;
}
now = now.AddDays(1);
}
}
So, if you just want to create weekends as non work days then you'd get the total like this:
var weekdays = WorkDaysInMonth(2020, 1, d => d.DayOfWeek == DayOfWeek.Saturday || d.DayOfWeek == DayOfWeek.Sunday);
var total = weekdays.Count();
Likewise if you've got some calendar system that tells you about public holidays then you can add a call into the predicate to see if the supplied date is a holiday.
var s = "January 2020";
var d = DateTime.Parse(s);
Console.WriteLine(d);
var x = DateTime.DaysInMonth(d.Year, d.Month);
Console.WriteLine(x);
var w = Enumerable.Range(1, x)
.Select( i => new DateTime( d.Year, d.Month, i))
.Count( i => i.DayOfWeek != DayOfWeek.Saturday && i.DayOfWeek != DayOfWeek.Sunday );
Console.WriteLine(w);
Demo: https://dotnetfiddle.net/sp3qYo

c# datetime create Day of Week Hour and Min [closed]

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 6 years ago.
Improve this question
How do i go about creating a datetime based on only the following information:
Day of Week, Hour & Minuet.
I.e. I don't care what month it is or even what the date is (i don't have that info in the database).
I thought i could parse them as a string but is turning out to be more difficult than i thought.
Created on function for you it might be helpful to you ..
public DateTime CreateDayOfWeek(int DayOfWeek,int hour,int min)
{
DateTime dt = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,hour,min,0);
// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
int daysUntilTuesday = (DayOfWeek - (int)dt.DayOfWeek + 7) % 7;
// DateTime nextTuesday = today.AddDays(daysUntilTuesday);
dt = dt.AddDays(daysUntilTuesday);
return dt;
}
I have tested for several dates and its working for me ..
let me know if you have any issue ..
Here is .netFiddle
You can create your date like this...
var hour = 1; // you set this from code
var minute = 1; // set this from code
var now = DateTime.Now;
var tempDateTime = new DateTime(now.Year, now.Month, now.Day, hour, minute, 0);
// Make this enum whatever you want your date to be...
var num = (int)DayOfWeek.Sunday;
var dateForComparison = tempDateTime.AddDays(num - (int)tempDateTime.DayOfWeek);
Now dateForComparison holds a date that has your time values set and the day of week you have specified.
You said you don't care about what month or date it is, which makes me assume you want any date as long as it is the right day of week and time (hour and minute). You can do it like this:
var date = new System.DateTime(2016, 9, 25);
date = date.AddDays(dow).AddHours(hours).AddMinutes(minutes);
September 25, 2016 was a Sunday. Add the day of the week (Sunday = 0) and you get the correct day. Then add the hours and minutes. Of course, if you like you can pick any Sunday of any month/year to start.
You can create a function for build your date:
public DateTime BuildDate(Int32 day, Int32 hour, Int32 minute)
{
var now = DateTime.Now;
var initialDate = now.AddDays(((Int32)now.DayOfWeek + 1) * -1);
return new DateTime(initialDate.Year, initialDate.Month, initialDate.AddDays(day).Day, hour, minute, 0);
}
The day of week is start from sunday in this case.
You can use: DateTime.ToString Method (String)
DateTime.Now.ToString("ddd HH:mm") // for military time (24 hour clock)
More: https://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Find next leap year from today's date in c#

I want to find the next leap year from today's date.
For ex.,
Date NextLeapDate
----- ------------
2016-01-01 2016-02-29
2016-05-24 2020-02-29
2017-02-03 2020-02-29
This is what I have so far to get the next leap year but it's getting me wrong value,
public int GetNextLeapYear(int year)
{
bool isLeapYear = false;
while (true)
{
if (DateTime.IsLeapYear(year))
{
isLeapYear = true;
}
else
{
year = year + 1;
GetNextLeapYear(year);
}
break;
}
return year;
}
Something like this:
DateTime GetNextLeapDate (DateTime baseDate)
{
int year = baseDate.Year;
// start in the next year if we’re already in March
if (baseDate.Month > 2)
year++;
// find next leap year
while (!DateTime.IsLeapYear(year))
year++;
// get last of February
return new DateTime(year, 2, 29);
}
Note that we need to skip checking the current year if (and only if) the base date is already ahead of March (i.e. a possible leap day is already over). That way, we don’t get a result of February 29th, 2016 for e.g. today (time of this post).
Used like this, it returns the desired dates:
Console.WriteLine(GetNextLeapDate(new DateTime(2016, 01, 01))); // 2016-02-29
Console.WriteLine(GetNextLeapDate(new DateTime(2016, 05, 24))); // 2020-02-29
Console.WriteLine(GetNextLeapDate(new DateTime(2017, 02, 03))); // 2020-02-29
You don't need recursion. Try this:
public int GetNextLeapYear(int year)
{
while (true)
{
if (DateTime.IsLeapYear(year))
{
return year;
}
year = year + 1;
}
}
Your current code is only a part of the program? The below code is copied from the question and changed with my suggestion edit (as well as other simplifications) to make it work correctly.
public int GetNextLeapYear(int year)
{
if (DateTime.IsLeapYear(year))
{
return year;
}
else
{
year = year + 1;
return GetNextLeapYear(year);
}
}
To use recursion to find the next leap year, you can change your method like so.
public int GetNextLeapYear(int year)
{
if (!DateTime.IsLeapYear(year))
{
return GetNextLeapYear(year + 1);
}
return year;
}
Using recursion, you don't need the While loop, you just need to check to see if you need to continue or return the value. This also allows you to get rid of variables that are not needed. #poke answer is more complete counting for the actual month that you are in and such. I only answered this way to keep with using recursion like you had done.

Why my C# program doesn't display Birthday reminders? [closed]

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

C# Linq to Entities get records where date range contains dates in the current month

I have Holiday EF Entity:
public class Holiday {
public int HolidayId {
get;
set;
}
public DateTime StartDate {
get;
set;
}
public DateTime EndDate {
get;
set;
}
public bool IsActive {
get;
set;
}
}
I need to get all records that has at least one day within the current month.
For example:
StartDate = "2014-06-29"
EndDate = "2014-07-03"
If current month is July then I should get that record, because after that I will have to create a List<int> of all the days affecting current month. So in the last sample I will have to create a List<int> of:
1,2 and 3 of July.
For example:
StartDate = "2014-07-23"
EndDate = "2014-08-01"
I should get that record also.
I was doing:
var holidays = Holidays.Where(h=> h.IsActive == true && h.StartDate < currentDate && h.EndDate > currentDate).ToList();
But, the query is not doing what I need.
Any clue?
What about this:
.Where(h => h.IsActive == true && (h.StartDate.Month == currentDate.Month || h.EndDate.Month == currentDate.Month)).ToList();
UPDATED:
This won't work when I have a date range where it's month is not equal to currentDate.Month. Like:
StartDate = "2014-06-29"
EndDate = "2014-08-03"
The solution that worked is:
Maybe is not the cleanest.
var holidays = Uow.HolidayRepository.GetAllReadOnly().Where(h => h.IsActive == true && (h.StartDate.Month == currentDate.Month || h.EndDate.Month == currentDate.Month) || (currentDate.Month > h.StartDate.Month && currentDate.Month < h.EndDate.Month)).ToList();
Neither test is sufficient: if the current date is today in then the first test will miss any date ranges that don't include the current date so if today is the first of the month any date range starting on the second although valid won't be caught. In addition single day ranges - unless you are including times won't be caught because the start and end dates could be equal to the current date but can never be greater than and less than - depends how you spec your date range.
The second test fails firstly because every year has months 1- 12 so not only will you be picking records for this year but for all years and secondly you miss any periods that start and end outside of the month.
Creating a list of days to compare doesn't sound efficient minimum number of runs 28 max 31.
So you need to test for ranges that either start in the current month or end in the current month as per Daniels code but in addition you need to test where the start date is before the current month and the end date is after the current month I think that should cover all cases?
I think this will do,please try it out:
int month = DateTime.Now.Month;
var result = Holidays.AsEnumerable().Where(h => Enumerable.Range(h.StartDate.Month, (h.EndDate.Month - h.StartDate.Month) + 1).Contains(month));

Categories