Get all the dates of the month from Day of week - c#

Is there any way to get all the occuring date for the particular day of the specified month and year..
For example:- If I have Day Thursday then I need all the dates of December 2016. Then collection should contain dates 1/12/2016, 8/12/2016, 15/12/2016, 22/12/2016, 29/12/2016.

You can create a function to get the list of dates of the month based on day of a particular year like
public static List<DateTime> GetDates(int year, int month,string day)
{
return Enumerable.Range(1, DateTime.DaysInMonth(year, month))
.Where(d=>new DateTime(year, month, d).ToString("dddd").Equals(day))
.Select(d => new DateTime(year, month, d)).ToList();
}
Now call this function like
var dates=GetDates(2016,12,"Thursday");
foreach(var d in dates){
Console.WriteLine(d.ToString());
}
Output will be
12/1/2016 12:00:00 AM
12/8/2016 12:00:00 AM
12/15/2016 12:00:00 AM
12/22/2016 12:00:00 AM
12/29/2016 12:00:00 AM
Now you have complete list of dates based on a day. You can further use it based on your requirements.

DateTime decFirst = new DateTime(2016, 12, 1);
int offset = (int)decFirst.DayOfWeek;
DateTime decThursday = decFirst.AddDays(offset);
Now you have the first Thursday of December, you should be able to do the rest.

Long form version...
private void button1_Click(object sender, EventArgs e)
{
List<DateTime> Thursdays = DaysOfMonth(2016, 12, DayOfWeek.Thursday);
foreach(DateTime dt in Thursdays)
{
Console.WriteLine(dt.ToString());
}
}
public static List<DateTime> DaysOfMonth(int year, int month, DayOfWeek day)
{
List<DateTime> dates = new List<DateTime>();
for (int i = 1; i <= DateTime.DaysInMonth(year, month); i++)
{
DateTime dt = new DateTime(year, month, i);
if (dt.DayOfWeek == day)
{
dates.Add(dt);
}
}
return dates;
}

Related

Combine Monday to Sunday dates to textfile

This is a C# 4.0 WinForms app.
I'm trying to pull all the Monday dates in a given month (the fully spelled out Month name and day), and the days in all the Sundays. Then, using StreamWriter, write these to a text file.
I found the following code suggestion on enumerating through a month, on StackOverFlow below.
How to get every monday of given month?
public static IEnumerable<DateTime> AllDatesInMonth(int year, int month)
{
int days = DateTime.DaysInMonth(year, month);
for (int day = 1; day <= days; day++)
{
yield return new DateTime(year, month, day);
}
}
And then you can call with LINQ like so:
var mondays = AllDatesInMonth(2017, 7).Where(i => i.DayOfWeek == DayOfWeek.Monday);
I modified the suggestion to also pull the Sunday dates. I'm testing this, in order to make it part of a larger application.
This is what I've come up with so far, as shown below.
private void btnTestDayOWeek_Click(object sender, EventArgs e)
{
int curYear = DateTime.Now.Year;
int month = DateTime.Now.Month;
string outputFile = #"C:\dates2Compare.txt";
List<string> mondayList = new List<string>();
List<string> sundayList = new List<string>();
using (StreamWriter sw = new StreamWriter(outputFile))
{
var mondays = AllDatesInMonth(curYear, 3).Where(i => i.DayOfWeek == DayOfWeek.Monday);
var sundays = AllDatesInMonth(curYear, 3).Where(i => i.DayOfWeek == DayOfWeek.Sunday);
foreach (DateTime Monday in mondays)
{
mondayList.Add(Monday.ToString("MMMM d"));
}
foreach (DateTime Sunday in sundays)
{
sundayList.Add(Sunday.ToString("-d"));
}
var dayList = mondayList.Concat(sundayList);//attempt to join these 2-Lists
foreach (string dt in dayList)
{
sw.WriteLine(dt);
}
}
}
public static IEnumerable<DateTime> AllDatesInMonth(int year, int month)
{
int days = DateTime.DaysInMonth(year, month);
for (int day = 1; day <= days; day++)
{
yield return new DateTime(year, month, day);
}
}
I need to join the Monday to Sunday dates, like this, i.e.
March 1-7
March 8-14
But this is what I'm receiving so far.
March 1
March 8
March 15
March 22
March 29
-7
-14
-21
-28
Can someone suggest how to modify my code so that, the text file that is written to, correctly displays the Monday date with a "-" after it and then the Sunday date?
You are making it too complicated. Simply loop the days of the month in a split second:
int year = 2021;
int month = 3;
DateTime date = new DateTime(year, month, 1);
string monthName = date.ToString("MMMM");
int ultimo = date.AddMonths(1).AddDays(-1).Day;
for (int i = 0; i < ultimo - 6; i++)
{
DateTime monthDate = date.AddDays(i);
if (monthDate.DayOfWeek == DayOfWeek.Monday)
{
string line = string.Format(monthName + " {0}-{1}", monthDate.Day, monthDate.Day + 6);
Console.WriteLine(line);
// sw.WriteLine(line);
}
}
Output:
March 1-7
March 8-14
March 15-21
March 22-28
//var dayList = mondayList.Concat(sundayList);//attempt to join these 2-Lists
List<string> dayList = new List<string>();
int weekCount = Math.Min(mondayList.Count(), sundayList.Count());
for (int i = 0; i < weekCount; i++)
{
string concateValue = mondayList[i] + sundayList[i];
dayList.Add(concateValue);
}
When you Concat lists, the values stack on top of each other. You need to merge the lists together.

DateTime get day of year

I want my new year to start at 14 March. Given any DateTime I want to get the day of year? How can I accomplish this with DateTime?
March 14 is the 73rd day of the year (74th in leap years) in the Gregorian calendar. 292 days remain until the end of the year. Is there a way I can define the new year of a year with DateTime?
int DayOfYear(DateTime date, int yearStartMonth, int yearStartDay)
{
var yearStart = new DateTime(d.Year, yearStartMonth, yearStartDay);
if(yearStart > d)
yearStart = yearStart.AddYears(-1);
return (d - yearStart).Days + 1;
}
try to use:
public static int DayOfYear(DateTime date)
{
var startDate= new DateTime(year:date.Year,month:3,day:14); //14 March
var diffDateDays=(date- startDate).Days;
if (diffDateDays > 0) return diffDateDays;
startDate= new DateTime(year:date.Year-1,month:3,day:14); //14 March of previous year
return (date- startDate).Days;
}

How to Calculate the Date when Given Month, DayOfWeek and WeekOfMonth?

I need to calculate holidays which always occur on varying day in a certain week every year. They usually occur on a first weekday in a specific week and month.
I have these properties: Name, Month, DayOfWeek, WeekOfMonth. How do I use DateTime objects to calculate the Day that the holiday falls on?
Notice in the code below how they handle Labor Day and Thanksgiving. You'll probably have to do something like this for other holidays that don't always fall on a specific date.
I got this code from U.S. Holiday List in C#
private static HashSet<DateTime> GetHolidays(int year)
{
HashSet<DateTime> holidays = new HashSet<DateTime>();
//NEW YEARS
DateTime newYearsDate = AdjustForWeekendHoliday(new DateTime(year, 1, 1).Date);
holidays.Add(newYearsDate);
//MEMORIAL DAY -- last monday in May
DateTime memorialDay = new DateTime(year, 5, 31);
DayOfWeek dayOfWeek = memorialDay.DayOfWeek;
while (dayOfWeek != DayOfWeek.Monday)
{
memorialDay = memorialDay.AddDays(-1);
dayOfWeek = memorialDay.DayOfWeek;
}
holidays.Add(memorialDay.Date);
//INDEPENCENCE DAY
DateTime independenceDay = AdjustForWeekendHoliday(new DateTime(year, 7, 4).Date);
holidays.Add(independenceDay);
//LABOR DAY -- 1st Monday in September
DateTime laborDay = new DateTime(year, 9, 1);
dayOfWeek = laborDay.DayOfWeek;
while(dayOfWeek != DayOfWeek.Monday)
{
laborDay = laborDay.AddDays(1);
dayOfWeek = laborDay.DayOfWeek;
}
holidays.Add(laborDay.Date);
//THANKSGIVING DAY - 4th Thursday in November
var thanksgiving = (from day in Enumerable.Range(1, 30)
where new DateTime(year, 11, day).DayOfWeek == DayOfWeek.Thursday
select day).ElementAt(3);
DateTime thanksgivingDay = new DateTime(year, 11, thanksgiving);
holidays.Add(thanksgivingDay.Date);
DateTime christmasDay = AdjustForWeekendHoliday(new DateTime(year, 12, 25).Date);
holidays.Add(christmasDay);
return holidays;
}
public static DateTime AdjustForWeekendHoliday(DateTime holiday)
{
if (holiday.DayOfWeek == DayOfWeek.Saturday)
{
return holiday.AddDays(-1);
}
else if (holiday.DayOfWeek == DayOfWeek.Sunday)
{
return holiday.AddDays(1);
}
else
{
return holiday;
}
}

How calculate if a Date is 6 month later birthdate in C#

how can I calculate if a date (in DateTime format) is 6 month later or not from my BirthDate (in DateTime format)?
Use DateTime AddMonth method
https://msdn.microsoft.com/ru-ru/library/system.datetime.addmonths(v=vs.110).aspx
var dat = new DateTime(2015, 12, 31);
var dat2 = new DateTime(2015, 12, 31);
if (dat.AddMonths(6) < dat2) { ... }
You should use DateTime.AddMonths :
DateTime dt;
DateTime birthDate;
if (dt <= birthDate.AddMonths(6))
{
}
enter your birth date, calculate your next birthday and compare the dates,
var born = new DateTime(1900, 02, 01);
var checkdate = DateTime.Now;
var nextBirthday = new DateTime(DateTime.Now.Year, born.Month, born.Day);
if (nextBirthday < DateTime.Now)
{
nextBirthday = new DateTime(DateTime.Now.Year + 1, born.Month, born.Day);
}
if (checkdate.AddMonths(6) < nextBirthday)
{
Console.WriteLine("date is 6 months later then birthday");
}
else
{
Console.WriteLine("wait for it");
}
DateTime birthDate=new DateTime(year,month,day);
DateTime dateToCompare = new DateTime(year, month, day);
if(dateToCompare >= birthdate.AddMonths(6))
{
//DoSomething
}
You could calculte the difference between dates using Subtract method and calculate how many months you have between these dates, for sample:
DateTime birthDay = /* some date */;
DateTime someDate = /* some date */;
var months = someDate.Subtract(birthDay).Days / (365.25 / 12);
This answer provides a good helper for Dates:
https://stackoverflow.com/a/33287670/316799

Get range of days in a week given a certain day

Suppose my input is March 31, 2015.
How would I be able to get the days of the week that March 31, 2015 is in?
In this case, it should output:
March 29, 2015-April 4, 2015
I found something similar here but it's not quite what I'm looking for as that one takes in the week number while my input is a date itself.
DateTime date = new DateTime(2015, 3, 31);
DateTime weekFirstDay = date.AddDays(DayOfWeek.Sunday - date.DayOfWeek);
DateTime weekLastDay = weekFirstDay.AddDays(6);
Here is a way to get each value separately from a given DateTime
Week start:
public static DateTime GetWeekStartDate(DateTime value)
{
return value.AddDays(-(int)value.DayOfWeek).Date;
}
Week end:
public static DateTime GetWeekEndDate(DateTime value)
{
return value.AddDays(6 - (int)value.DayOfWeek).Date;
}
DayOfWeek firstDayOfWeek = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
DateTime startDate = DateTime.Now;
while (firstDayOfWeek != startDate.DayOfWeek)
{
startDate = startDate.AddDays(-1);
}
DateTime firstDay = startDate.Date;
DateTime lastDay = startDate.AddDays(6);

Categories

Resources