I want to count occurrences, for each day of the week, between two given dates.
For example:
Between 20/07/2014 to 27/7/2014, an 8 day span, there were:
Sunday=2, monday=1, tuesday=1,...
Try this:
DateTime start = new DateTime(2014,07,20);
DateTime end = new DateTime(2014,07,27);
TimeSpan ts = end - start;
int limit = ts.Days;
var result = Enumerable.Range(0,limit+1)
.Select(x => start.AddDays(x))
.GroupBy(x => x.DayOfWeek)
.Select(x => new {day = x.Key, count = x.Count()});
We create a range of dates from start to end, inclusive of both dates, and then group by the day of week to get the days and corresponding counts.
Demo
You better convert the days first to DateTime instances:
DateTime d1 = new DateTime(2014,07,20);
DateTime d2 = new DateTime(2014,07,27);
Next you calculate the total days between the two dates:
int days = (int) Math.Floor((d2-d1).TotalDays)+1;
As well as the day of the week of the first date:
int dow = (int) d1.DayOfWeek;
Now we devide the number of days by seven and assign that number to all days: since this is the minimum occurences for each day:
int d7 = days/7;
int[] counts = new int[7];
for(int i = 0; i < 7; i++) {
counts[i] = d7;
}
The remainder of the days are distributed with the day of the week of d1 first:
int remainder = days-7*d7;
int dowi = dow;
while(remainder > 0) {
counts[dowi]++;
dowi = (dowi+1)%7;//next day of the week
remainder--;
}
Then we can return the arrray:
return counts;
Full method:
public static int[] countDelta (DateTime d1, DateTime d2) {
int days = (int) Math.Floor((d2-d1).TotalDays)+1;
int dow = (int) d1.DayOfWeek;
int d7 = days/7;
int[] counts = new int[7];
for(int i = 0; i < 7; i++) {
counts[i] = d7;
}
int remainder = days-7*d7;
int dowi = dow;
while(remainder > 0) {
counts[dowi]++;
dowi = (dowi+1)%7;//next day of the week
remainder--;
}
return counts;
}
The result of a csharp interactive session:
csharp> Foo.countDelta(new DateTime(2014,07,20),new DateTime(2014,07,27));
{ 2, 1, 1, 1, 1, 1, 1 }
The method runs in constant time (if the dates differ much, this will not have an impact on performance). The only constraint is that calendar must be modern: if somewhere in history, people skipped a few "days of the week", this could result in some problems.
You can try something like this. It may be not the best solution, but it's the first that came in mind:
var startDate = DateTime.Now;
var endDate = startDate.AddDays(15);
var rusultDictionary = new Dictionary<DayOfWeek, int>();
while (!startDate.Date.Equals(endDate.Date))
{
rusultDictionary[startDate.DayOfWeek] = rusultDictionary.ContainsKey(startDate.DayOfWeek) ? rusultDictionary[startDate.DayOfWeek] + 1 : 1;
startDate = startDate.AddDays(1);
}
the simple way is for loop each day in the period, and use switch case or if else to check the current date.DayOfWeek to count and save the week number, something like the following:
int mondays = 0;
switch(current.DayOfWeek){
case DayOfWeek.Monday:
mondays++;
break;
...
}
public static Dictionary<DayOfWeek, int> CountDayOfWeeks(DateTime #from, DateTime to)
{
var start = #from.Date;
var ret = Enum.GetValues(typeof(DayOfWeek)).Cast<DayOfWeek>().ToDictionary(x => x, x => 0);
while (start <= to)
{
ret[start.DayOfWeek]++;
start = start.AddDays(1);
}
return ret;
}
you can achieve it using Linq:
DateTime StartDate = DateTime.Now.AddDays(-14);
DateTime EndDate = DateTime.Now;
DayOfWeek day = DayOfWeek.Monday;
First get the all days between two dates:
List<DateTime> dates = Enumerable.Range(0, (int)((EndDate - StartDate).TotalDays) + 1)
.Select(n => StartDate.AddDays(n))
.ToList();
Now get Count on the base of day, currently it will get Count of Monday:
var MondayCount = dates.Count(x => x.DayOfWeek == day);
FIDDLE:
https://dotnetfiddle.net/ZopkFY
Related
I am struggling with a datetime problem where I am given a set of inputs and I need to find the EndDate by using those inputs. I am trying my best to solve this, but since I am running out of time, I landed up here. So someone who already might have faced this problem or someone with a solution could let me know one.
Problem Explanation:
The Concept is a Weekly schedule of a live class streaming application. The teacher has scheduled a weekly class from a specific start date.
Let's say, the start date is from 18th April, 2021 and the teacher selects 3 days per week(Monday, Tuesday & Wednesday) each with different class duration(By duration I mean that, We have the class start time of that day and the length of the class in hours and minutes).
Start Date: 18th April, 2021
Total days per week: 3
Days: Monday, Tuesday, Wednesday
Total duration per day: 3 hrs and 30 minutes
Total duration per week: 10 hours 30 minutes (Aggregated = Mon + Tue + Wed)
Max duration that the user cannot exceed: 50 hrs
Ok! Now we shall repeatedly add the TDPD(3 hrs and 30 minutes) to the start date until we reach 50 hrs and find which date it has landed upon(the end date).
What I have tried so far?
int totalWeeks = 0;
int totalHoursPerWeek = 3;
int totalHoursAdded = 0;
int maxHours = 50;
for(int i = totalHoursPerWeek; i <= maxHours; i += totalHoursPerWeek)
{
totalHoursAdded += i;
totalWeeks++;
}
Once the loop ends, I have the total week value.
DateTime endDate;
if(totalHoursAdded == maxHours)
{
//My problem is solved, as there is no remaining time pending
endDate = currentDate.AddDays(totalWeeks * 7);
}
else
{
// I have some pending hours
int pendingHours = maxHours - totalHoursAdded;
//How do I proceed with this pendingHours? how to add this to the
//specific days per week and find the end date? I am stuck here...
}
I am confident this can be done with some carefully thought-out math with dates, however below may be termed the lazy way out. This approach only needs the starting date, a list of days of the week that the class meets, i.e., Monday, Tuesday etc.…, the duration of the class in hours and minutes, and finally the max total hours and minutes that are required.
From my understanding, given the above info, we want to know, given that start date and the days of the week the class meets…
on what Date will the LAST class be that fulfills the max total hours.
To simplify this, one thing that will come in handy is knowing...
“how many classes are needed to fulfill the MAX requirement”.
In other words, if we know how many classes are needed to fulfill the max requirement, then this should make things easier.
Computing the total number of classes needed to fulfil the max requirement, can be found by dividing the max requirement by the class duration. If the division produces a remainder, then this would mean that one (1) additional class would be needed to fulfil the max requirement.
Therefore, if we have both the class duration and max duration variables as Timespan objects, then, we could divide the TimeSpan objects via their respective Tick properties and return how many classes are needed to fulfil the max requirement. This method may look something like…
private int GetTotalNumberOfClassesNeeded(TimeSpan classDuration, TimeSpan totalDuration) {
double td = totalDuration.Ticks / (double)classDuration.Ticks;
int totalClasses = (int)Math.Truncate(td); // <- get the whole portion
if (Math.Floor(td) != td) {
totalClasses++; // <- there is a fractional part - 1 more class needed
}
return totalClasses;
}
Next, we need to compare the DayOfWeek for a date with the DayOfWeek for the class. Therefore, is what we can do is create a List<DayOfWeek> … a list of DayOfWeek objects that the class is in session. We will use this list to check and see if a particular date’s day of week is IN that list. Therefore, in this example, the days of the week the class meets are a simple comma delimited string. Given this string, the code would parse out the days and return the proper list of DayOfWeek objects to compare with. This method may look something like…
private List<DayOfWeek> GetDaysOfWeekForClasses(string daysOfWeek) {
List<DayOfWeek> classesDOW = new List<DayOfWeek>();
string[] splitArray = daysOfWeek.Split(',');
DayOfWeek dow;
for (int i = 0; i < splitArray.Length; i++) {
switch (splitArray[i].Trim()) {
case "Monday":
dow = DayOfWeek.Monday;
break;
case "Tuesday":
dow = DayOfWeek.Tuesday;
break;
case "Wednesday":
dow = DayOfWeek.Wednesday;
break;
case "Thursday":
dow = DayOfWeek.Thursday;
break;
case "Friday":
dow = DayOfWeek.Friday;
break;
case "Saturday":
dow = DayOfWeek.Saturday;
break;
default:
dow = DayOfWeek.Sunday;
break;
}
classesDOW.Add(dow);
}
return classesDOW;
}
That is pretty much all we need. The general idea is this… we start by setting an int variable curClassCount to zero (0). In addition, we will create a DateTime object tempDate that is initialized with the starting date. Lastly, we will create a list of DateTime objects scheduledClasses which will get filled with the dates of the classes. We will start a while loop with the condition to continue as long as curClassCount is less than the total number of classes needed.
In each iteration of the loop a check is made to see if the tempDate’s DayOfWeek is one of the class’s DayOfWeek. … if it is, then we add that date to the scheduledClasses list and increment curClassCount. Finally increment tempDate by one (1) day, then start the loop over. Eventually, the curClassCount will equal the number of classes needed. This code may look something like…
while (curClassCount < totalNumberOfClassesNeeded) {
if (ClassDaysOfWeek.Contains(tempDate.DayOfWeek)) {
scheduledClasses.Add(tempDate.Date);
curClassCount++;
}
tempDate = tempDate.AddDays(1);
}
Putting all this together by droping a DateTimePicker, four (4) TextBoxes, a Button and a multi-line TextBox onto a new Winforms .Net Form may look something like…
Using the code below should complete the example.
private void Form1_Load(object sender, EventArgs e) {
dateTimePicker1.Value = new DateTime(2021, 4, 18);
TextBoxTotDaysPerWeek.Text = "3";
textBoxClassDays.Text = "Monday, Tuesday, Wednesday";
textBoxClassDuration.Text = "00:03:00:00";
textBoxMaxDuation.Text = "02:02:00:00";
}
private void btnCalculate_Click(object sender, EventArgs e) {
DateTime StartDate = dateTimePicker1.Value;
TimeSpan.TryParse(textBoxClassDuration.Text.Trim(), out TimeSpan ClassDuration);
TimeSpan.TryParse(textBoxMaxDuation.Text.Trim(), out TimeSpan MaxDuration);
int totalNumberOfClassesNeeded = GetTotalNumberOfClassesNeeded(ClassDuration, MaxDuration);
List<DayOfWeek> ClassDaysOfWeek = GetDaysOfWeekForClasses(textBoxClassDays.Text.Trim());
List<DateTime> scheduledClasses = new List<DateTime>();
int curClassCount = 0;
DateTime tempDate = StartDate.Date;
while (curClassCount < totalNumberOfClassesNeeded) {
if (ClassDaysOfWeek.Contains(tempDate.DayOfWeek)) {
scheduledClasses.Add(tempDate.Date);
curClassCount++;
}
tempDate = tempDate.AddDays(1);
}
txtBoxResults.Text = "";
txtBoxResults.Text = "Start Date: " + StartDate.ToShortDateString() +Environment.NewLine;
for (int i = 0; i < scheduledClasses.Count; i++) {
txtBoxResults.Text += "Class # " + (i + 1) + " of " + totalNumberOfClassesNeeded +
" Date: " + scheduledClasses[i].ToShortDateString() + Environment.NewLine;
}
}
A note, on the max duration… since the TimeSpan only allows hours < 23, we need to break 50 hours into 2 days and 2 hours. I hope this makes sense.
These are two options (using For and using While loop), should solve the problem:
using System;
namespace SO.DtProblem
{
class Program
{
static void Main(string[] args)
{
ClaculationOption1(); //Using For loop
ClaculationOption2(); //Using While loop
}
private static void ClaculationOption1()
{
var totalWeeks = 0;
var totalHoursPerWeek = 3;
var durationPerDay = 3;
var maxHours = 50;
var courseStartDate = new DateTime(2021, 4, 12); //Which is a Monday day
totalWeeks = maxHours / totalHoursPerWeek;
var expectedEndDate = courseStartDate.AddDays(totalWeeks * 7);
var pendingHours = maxHours % totalHoursPerWeek;
for (var day = 1; day <= 6; day++)
{
if (pendingHours > 0)
{
expectedEndDate = expectedEndDate.AddDays(1);
if ((expectedEndDate.AddDays(1).DayOfWeek == DayOfWeek.Monday)
|| (expectedEndDate.AddDays(1).DayOfWeek == DayOfWeek.Tuesday)
|| (expectedEndDate.AddDays(1).DayOfWeek == DayOfWeek.Wednesday))
{
if (pendingHours - durationPerDay >= 0)
{
pendingHours = pendingHours - durationPerDay;
}
else
{
pendingHours = 0;
break;
}
}
}
}
Console.Clear();
Console.WriteLine("Option 1 Results");
Console.WriteLine($"Course Start Date : {courseStartDate}");
Console.WriteLine($"Course Start Date Day Name: {courseStartDate.DayOfWeek}");
Console.WriteLine($"Expected End Date : {expectedEndDate}");
Console.WriteLine($"Expected End Date Day Name: {expectedEndDate.DayOfWeek}");
Console.WriteLine("===========================================================");
}
private static void ClaculationOption2()
{
var totalWeeks = 0;
var totalHoursPerWeek = 3;
var durationPerDay = 3;
var maxHours = 50;
var courseStartDate = new DateTime(2021, 4, 12); //Which is a Monday day
totalWeeks = maxHours / totalHoursPerWeek;
var expectedEndDate = courseStartDate.AddDays(totalWeeks * 7);
var pendingHours = maxHours % totalHoursPerWeek;
while (pendingHours > 0)
{
expectedEndDate = expectedEndDate.AddDays(1);
if ((expectedEndDate.AddDays(1).DayOfWeek == DayOfWeek.Monday)
|| (expectedEndDate.AddDays(1).DayOfWeek == DayOfWeek.Tuesday)
|| (expectedEndDate.AddDays(1).DayOfWeek == DayOfWeek.Wednesday))
{
if (pendingHours - durationPerDay >= 0)
{
pendingHours = pendingHours - durationPerDay;
}
else
{
pendingHours = 0;
break;
}
}
}
Console.WriteLine("Option 2 Results");
Console.WriteLine($"Course Start Date : {courseStartDate}");
Console.WriteLine($"Course Start Date Day Name: {courseStartDate.DayOfWeek}");
Console.WriteLine($"Expected End Date : {expectedEndDate}");
Console.WriteLine($"Expected End Date Day Name: {expectedEndDate.DayOfWeek}");
Console.ReadKey();
}
}
}
Finally I got my own solution working on the idea based on #John's answer. This answer is specially for the variable hours and minutes.
private static void CalculateClassDates()
{
DateTime courseStartDateTime = DateTime.Today;
int courseDurationInHours = 60;
int courseDurationInMinutes = 0;
TimeSpan courseMaxDuration = new TimeSpan(courseDurationInHours, courseDurationInMinutes, 0);
List<CourseScheduleDates> courseScheduleDates = new List<CourseScheduleDates>();
List<DaysOfWeek> daysOfWeeks = new List<DaysOfWeek>()
{
new DaysOfWeek(){ DayOfWeek = DayOfWeek.Monday, StartTime = DateTime.Today.AddHours(10).TimeOfDay , TotalHours = 1, TotalMinutes = 15},
new DaysOfWeek(){ DayOfWeek = DayOfWeek.Tuesday, StartTime = DateTime.Today.AddHours(10).TimeOfDay , TotalHours = 1, TotalMinutes = 15},
new DaysOfWeek(){ DayOfWeek = DayOfWeek.Wednesday, StartTime = DateTime.Today.AddHours(10).TimeOfDay , TotalHours = 1, TotalMinutes = 30}
};
int daysToAdd = 0;
TimeSpan singleDuration = new TimeSpan(daysOfWeeks[0].TotalHours, daysOfWeeks[0].TotalMinutes, 0);
TimeSpan additionallyAddedTime = TimeSpan.Zero;
List<DayOfWeek> days = daysOfWeeks.Select(x => x.DayOfWeek).ToList();
while (singleDuration.Ticks <= courseMaxDuration.Ticks)
{
if (days.Contains(courseStartDateTime.AddDays(daysToAdd).DayOfWeek))
{
var dayOfWeek = daysOfWeeks.Where(x => x.DayOfWeek == courseStartDateTime.AddDays(daysToAdd).DayOfWeek).First();
courseScheduleDates.Add(new CourseScheduleDates()
{
ScheduleDate = courseStartDateTime.AddDays(daysToAdd),
StartTime = dayOfWeek.StartTime,
TotalHours = dayOfWeek.TotalHours,
TotalMinutes = dayOfWeek.TotalMinutes
});
additionallyAddedTime = new TimeSpan(dayOfWeek.TotalHours, dayOfWeek.TotalMinutes, 0);
singleDuration = singleDuration.Add(additionallyAddedTime);
}
daysToAdd++;
}
singleDuration = singleDuration.Subtract(additionallyAddedTime);
if (singleDuration.Ticks != courseMaxDuration.Ticks)
{
var timeSpanToAdd = new TimeSpan(courseMaxDuration.Ticks - singleDuration.Ticks);
bool shouldContinue = true;
while (shouldContinue)
{
var currentDate = courseStartDateTime.AddDays(daysToAdd);
if (days.Contains(currentDate.DayOfWeek))
{
var dayOfWeek = daysOfWeeks.Where(x => x.DayOfWeek == courseStartDateTime.DayOfWeek).First();
courseScheduleDates.Add(new CourseScheduleDates()
{
ScheduleDate = courseStartDateTime.AddDays(daysToAdd),
StartTime = dayOfWeek.StartTime,
TotalHours = timeSpanToAdd.Hours,
TotalMinutes = timeSpanToAdd.Minutes
});
shouldContinue = false;
}
}
}
Console.WriteLine("Course Start Date " + courseStartDateTime.ToString("dd MMM, yyyy"));
int classCount = 1;
foreach (var item in courseScheduleDates)
{
DateTime dateTime = new DateTime(item.StartTime.Ticks);
Console.WriteLine("Class " + classCount + " will commence on " + item.ScheduleDate.ToString("dd MMM, yyyy") +
" " + dateTime.ToString("hh:mm tt") + " and will last for " + item.TotalHours + " hrs " + item.TotalMinutes + " mins");
classCount++;
}
Console.ReadLine();
}
And the Models
public class DaysOfWeek
{
public DayOfWeek DayOfWeek { get; set; }
public TimeSpan StartTime { get; set; }
public int TotalHours { get; set; }
public int TotalMinutes { get; set; }
}
public class CourseScheduleDates
{
public DateTime ScheduleDate { get; set; }
public TimeSpan StartTime { get; set; }
public int TotalHours { get; set; }
public int TotalMinutes { get; set; }
}
I want to calculate the number of weeks within a month.
The first week of January 2014 starting from the first Monday is the 6th. So, January has 4 weeks.
The first week of March 2014 starting from the first Monday is the 3rd. So, March has 5 weeks.
I want to know how many weeks there are in a month counting from the first Monday, not the first day.
How do I do this?
I have this code but it is used to get week number of the month for specific dates.
public 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;
}
Try this:
Get the number of days in the current month, and find the first day. For each day in the month, see if the day is a Monday, if so, increment the value.
public static int MondaysInMonth(DateTime thisMonth)
{
int mondays = 0;
int month = thisMonth.Month;
int year = thisMonth.Year;
int daysThisMonth = DateTime.DaysInMonth(year, month);
DateTime beginingOfThisMonth = new DateTime(year, month, 1);
for (int i = 0; i < daysThisMonth; i++)
if (beginingOfThisMonth.AddDays(i).DayOfWeek == DayOfWeek.Monday)
mondays++;
return mondays;
}
You can use it like this with the current date:
Console.WriteLine(MondaysInMonth(DateTime.Now));
Output:
4
or with any month you choose:
Console.WriteLine(MondaysInMonth(new DateTime(year, month, 1)))
Just correction to Cyral code :
i must start from 0 as he is using AddDays method .
Reason :the above example returns 5 for NOV and 4 for DEC which is wrong..
Edited code :
public static int MondaysInMonth(DateTime thisMonth)
{
int mondays = 0;
int month = thisMonth.Month;
int year = thisMonth.Year;
int daysThisMonth = DateTime.DaysInMonth(year, month);
DateTime beginingOfThisMonth = new DateTime(year, month, 1);
for (int i = 0; i < daysThisMonth; i++)
if (beginingOfThisMonth.AddDays(i).DayOfWeek == DayOfWeek.Monday)
mondays++;
return mondays;
}
I tried to use that code, but in some cases it didn't work. So I found this code on MSDN.
public static int MondaysInMonth(this DateTime time)
{
//extract the month
int daysInMonth = DateTime.DaysInMonth(time.Year, time.Month);
var firstOfMonth = new DateTime(time.Year, time.Month, 1);
//days of week starts by default as Sunday = 0
var firstDayOfMonth = (int)firstOfMonth.DayOfWeek;
var weeksInMonth = (int)Math.Ceiling((firstDayOfMonth + daysInMonth) / 7.0);
return weeksInMonth;
}
I created it like a extension method, so I can use like that:
var dateTimeNow = DateTime.Now;
var weeks = dateTimeNow.MondaysInMonth();
The faster method without looping
private static double GetDaysCount(DateTime sampleDate, int DayOfWeekToMatch)
{
int FirstDayOfMonth = (int)(new DateTime(sampleDate.Year, sampleDate.Month, 1).DayOfWeek);
int FirstOccurrenceOn = 0;
if (FirstDayOfMonth < DayOfWeekToMatch)
FirstOccurrenceOn = DayOfWeekToMatch - FirstDayOfMonth + 1;
else
FirstOccurrenceOn = (7 - FirstDayOfMonth) + DayOfWeekToMatch + 1;
int totalDays = DateTime.DaysInMonth(sampleDate.Year, sampleDate.Month);
return Math.Ceiling((totalDays - FirstOccurrenceOn) / 7.0f);
}
How to get The dates in a specific week given the month and the year ?
For example:
My parameters :
June - 2013 - The second week
I want the result set like this :
9-6-2013
10-6-2013
11-6-2013
12-6-2013
13-6-2013
I want it starting from Sun to Thu .
Well in my Noda Time library I would:
Start from the end of the previous month
Loop as many times as you want finding the next Sunday
Go from there, yielding the days (so you can just use a foreach loop):
So:
IEnumerable<LocalDate> GetSundayToWednesday(int year, int month, int week)
{
LocalDate date = new LocalDate(year, month, 1).PlusDays(-1);
for (int i = 0; i < week; i++)
{
date = date.Next(IsoDayOfWeek.Sunday);
}
// You always want 4 days, Sunday to Wednesday
for (int i = 0; i < 4; i++)
{
yield return date;
date = date.PlusDays(1);
}
}
Using just DateTime, I'd probably start at the first day of the month that it could be (week * 7 + 1) and loop until I hit the right day of week, then go from there:
IEnumerable<DateTime> GetSundayToWednesday(int year, int month, int week)
{
// Consider breaking this part out into a separate method?
DateTime date = new DateTime(year, month, week * 7 + 1);
for (int i = 0; i < 7; i++)
{
if (date.DayOfWeek == DayOfWeek.Sunday)
{
break;
}
date = date.AddDays(1);
}
// You always want 4 days, Sunday to Wednesday
for (int i = 0; i < 4; i++)
{
yield return date;
date = date.AddDays(1);
}
}
Looping like this isn't terribly efficient - you could just work out how many days to advance - but it's more obviously right. You can very easily end up with off-by-one errors (or going back into the previous month) with a more efficient approach. You may choose to put more effort into being efficient if this is important, of course.
I have not really tested this but I think that does more or less what you want:
int year = 2013;
int month = 6;
int lookupWeek = 2;
int daysInMonth = DateTime.DaysInMonth(year, month);
int weekCounter = 1;
List<DateTime> weekDays = new List<DateTime>();
for (int day = 1; day <= daysInMonth; day++)
{
DateTime date = new DateTime(year,month,day);
if(date.DayOfWeek == DayOfWeek.Sunday && day > 1) weekCounter++;
if(weekCounter == lookupWeek) weekDays.Add(date);
}
If you are interested in the client-side (JavaScript) route, then date.js might be worth a look, it allows for the following:
// What date is next thursday?
Date.today().next().thursday();
// Add 3 days to Today
Date.today().add(3).days();
// Is today Friday?
Date.today().is().friday();
// Number fun
(3).days().ago();
// 6 months from now
var n = 6;
n.months().fromNow();
// Set to 8:30 AM on the 15th day of the month
Date.today().set({ day: 15, hour: 8, minute: 30 });
// Convert text into Date
Date.parse('today');
Date.parse('t + 5 d'); // today + 5 days
Date.parse('next thursday');
Date.parse('February 20th 1973');
Date.parse('Thu, 1 July 2004 22:30:00');
I find the natural language syntax (i.e. 'next thursday') to be quite powerful.
This method gives the days in a specific week of a month:
static IEnumerable<string> DaysInWeek(int year, int month, int week)
{
var date = new DateTime(year, month, 1);
var calendar = new GregorianCalendar();
var firstWeek = calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFullWeek, DayOfWeek.Sunday);
var days = calendar.GetDaysInMonth(year, month);
var daysInWeek = (from day in Enumerable.Range(0, calendar.GetDaysInMonth(year, month) - 1)
let dayDate = date.AddDays(day)
let week2 = calendar.GetWeekOfYear(dayDate, CalendarWeekRule.FirstFullWeek, DayOfWeek.Sunday) - firstWeek + 1
where week2 == week
select day + 1).ToList();
foreach (var d in daysInWeek) yield return string.Format("{0:00}-{1:00}-{2:0000}", d, month, year);
}
And the output of this:
foreach (var d in DaysInWeek(week, year, month).Take(5)) Log.Info(d);
Would be:
09-06-2013
10-06-2013
11-06-2013
12-06-2013
13-06-2013
Note: I have edited the code. There was a little bug; because in many months, first week and last week are not complete weeks and some days of that week belongs to another month.
If you were keen to use linq (I almost always am!), you could do this:
int year = 2013;
int month = 6;
int weekOfMonth = 2;
var dates = Enumerable.Range(1, DateTime.DaysInMonth(year, month))
.Select(day => new DateTime(year, month, day))
.GroupBy(g=> g.DayOfYear/7)
.ToList();
var week = dates.Min(g => g.Key) + weekOfMonth - 1;
var result = dates.Where(g=> g.Key.Equals(week)).Select(g => g.ToList());
try this
protected void button_click(object sender, EventArgs e)
{
DateTime dt = new DateTime(2013, 6, 1);
string[] dates = getDates(dt);
}
public string[] getDates(DateTime dt)
{
string[] result = new string[7]; ;
for (int i = getDay(dt.DayOfWeek.ToString()); i < 7; i++)
{
if (i == 0)
{
break;
}
else
{
dt = dt.AddDays(1);
}
}
for (int i = 0; i < 7; i++)
{
dt = dt.AddDays(1);
result[i] = dt.ToShortDateString();
}
return result;
}
public int getDay(string day)
{
switch (day)
{
case "Monday":
return 0;
case "Tuesday":
return 1;
case "Wednesday":
return 2;
case "Thursday":
return 3;
case "Friday":
return 4;
case "Saturday":
return 5;
case "Sunday":
return 6;
default:
return 0;
}
}## Heading ##
I have two text-boxes which are used to select a From and a To date. I need to have a loop where the outer loop will be for a year and the inner loop will run for each month.
Problem is with the code below, if I choose 11/01/2011 and 06/30/2012, my month loop runs once for month 11. After that the loop exits.. Any help is appreciated.
I'm using the code below to look into a SharePoint Calendar List (using CAML query) and fetch number of times 3, 5 consecutive days a certain room is available excluding week ends. Idea is to use CAML query to get the number of free days for each month and keep repeating till the last selected month.
int year = 0, month = 0;
for (year = Calendar1.SelectedDate.Year; year <= Calendar2.SelectedDate.Year; year++)
{
int i = year;
for (month = Calendar1.SelectedDate.Month; month <= Calendar2.SelectedDate.Month; month++)
{
int j = month;
}
}
Would something like this work?
for (DateTime date = Calendar1.SelectedDate; date < Calendar2.SelectedDate; date = date.AddMonths(1))
{
//code
}
If I understand you correctly you want to iterate through each month between the 2 dates. If so, this should work:
var dt2 = Calendar2.SelectedDate.Year;
var current = Calendar1.SelectedDate;
while (current < dt2)
{
current = current.AddMonths(1);
//do your work for each month here
}
Your starting and ending number for your inner loop should be conditional.
If you're on the start year then the start month should be the selected month; otherwise it should be 1.
If you're on the end year then the end month should be the selected month; otherwise it should be 12.
Example:
var startYear = Calendar1.SelectedDate.Year;
var endYear = Calender2.SelectedDate.Year;
var startMonth = Calender1.SelectedDate.Month;
var endMonth = Calender2.SelectedDate.Month;
for (var year = startYear; year <= endYear; year++)
{
var sm = year == startYear ? startMonth : 1;
var em = year == endYear ? endMonth : 12;
for (var month = sm; month <= em; month++)
{
}
}
For the start year, you need to start your inner loop from the appropriate month, and run through all 12 months, except on the end year, where you should run to the appropriate month. Something like this should work:
int year = 0, month = 0;
for (year = Calendar1.SelectedDate.Year; year <= Calendar2.SelectedDate.Year; year++)
{
int i = year;
for (month = (i==Calendar1.SelectedDate.Year ? Calendar1.SelectedDate.Month : 1); month <= (i==Calendar2.SelectedDate.Year ? Calendar2.SelectedDate.Month : 12); month++)
{
int j = month;
}
}
//Function return First day in Month For Date --example : 01-09-2012
public static DateTime FirstDayOfMonthFromDateTime(DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, 1);
}
//code used to loop throw a Date range for each month
DateTime FirstDayInMonth = FirstDayOfMonthFromDateTime(Date);
DateTime TempDay = FirstDayInMonth;
int days = DateTime.DaysInMonth(FirstDayInMonth.Year, FirstDayInMonth.Month);
for (int i = 0; i < days; i++)
{
System.Out.Println(TempDay.toString());
TempDay.AddDays(1);
}
//then used code for each month in year (simple loop from 1-12)..
private static void Main(string[] args)
{
Console.WriteLine(DateTime.DaysInMonth(2020, 1));
var start = new DateTime(1900, 1, 1);
var end = new DateTime(2000, 12, 31);
end = new DateTime(end.Year, end.Month, DateTime.DaysInMonth(end.Year, end.Month));
var diff = Enumerable.Range(0, Int32.MaxValue)
.Select(e => start.AddMonths(e))
.TakeWhile(e => e <= end)
.Select(e => e);
foreach (var item in diff)
{
Console.WriteLine("Start Date - " + item.ToString("dd-MM-yyyy"));
Console.WriteLine("End Date - " + item.AddDays(DateTime.DaysInMonth(item.Year, item.Month) - 1).ToString("dd-MM-yyyy"));
}
}
I have got the following, but its not quite what I need now - It returns the dates of all the Fridays for the month passed in.
public static IEnumerable<DateTime> ReturnNextNthWeekdaysOfMonth(DateTime dt, DayOfWeek weekday, int amounttoshow = 4)
{
var days =
Enumerable.Range(1, DateTime.DaysInMonth(dt.Year, dt.Month)).Select(
day => new DateTime(dt.Year, dt.Month, day));
var weekdays = from day in days
where day.DayOfWeek == weekday
orderby day.Day ascending
select day;
return weekdays.Take(amounttoshow);
}
HOWEVER I now want to return the next Nth Fridays dates from todays date, irrelavant of the month they are in.
And I'm a bit stuck... Any help greatly appreciated.
What about trying this...
public static List<DateTime> ReturnNextNthWeekdaysOfMonth(DateTime dt, DayOfWeek weekday, int amounttoshow = 4)
{
List<DateTime> list = new List<DateTime>();
dt = dt.AddDays(weekday - dt.DayOfWeek);//set to the first day in the list
if (weekday <= dt.DayOfWeek)
dt = dt.AddDays(7);
for (int i = 0; i < amounttoshow; i++)
{
list.Add(dt);
dt = dt.AddDays(7);
}
return list;
}
Note that as it stands, if you pass in the current day then the first date in the list will be next week and not today. If you want today to be included as the first date in this instance you can using the following code instead....
public static IEnumerable<DateTime> ReturnNextNthWeekdaysOfMonth(DateTime dt, DayOfWeek weekday, int amounttoshow = 4)
{
List<DateTime> list = new List<DateTime>();
if (weekday < dt.DayOfWeek)
dt = dt.AddDays(7);
dt = dt.AddDays(weekday - dt.DayOfWeek);
for (int i = 0; i < amounttoshow; i++)
{
list.Add(dt);
dt = dt.AddDays(7);
}
return list;
}
public static IEnumerable<DateTime> ReturnNextNthWeekdaysOfMonth(DateTime dt, DayOfWeek weekday, int amounttoshow = 4)
{
// Find the first future occurance of the day.
while(dt.DayOfWeek != weekday)
dt = dt.AddDays(1);
// Create the entire range of dates required.
return Enumerable.Range(0, amounttoshow).Select(i => dt.AddDays(i * 7));
}
This first looks for the next day matching weekday then proceeds to create amounttoshow DateTime instances each of which is 7 days further than the previous, starting at the found date.
No need to bother with LINQ:
public static IEnumerable<DateTime> ReturnNextNthWeekdaysOfMonth(DateTime dt, DayOfWeek weekday, int amounttoshow = 4)
{
while(dt.DayOfWeek != weekday)
dt = dt.AddDays(1);
for (int i = 0; i < amounttoshow; i++)
{
yield return dt;
dt = dt.AddDays(7);
}
}
Change last line to
return weekdays.Where((x, i) => i % N == 0);
replace the complete method body with
return (from z in Enumerable.Range (0, amounttoshow)
let b = (from x in Enumerable.Range (0, 6) where DateTime.Now.AddDays (x).DayOfWeek == weekday select DateTime.Now.AddDays (x)).First()
select b.AddDays (z * 7));
Try this
public static IEnumerable<DateTime> ReturnNextNthWeekdaysOfMonth(DateTime dt, DayOfWeek weekday, int amounttoshow = 4)
{
// get the difference from the weekday
int diff = dt.DayOfWeek - weekday;
// amounttoshow * 7 is the number of days in a week (28 to get 4 weeks)
var days =
Enumerable.Range(1, amounttoshow * 7 + diff).Select(
day => DayOfYear(dt, day));
var weekdays = from day in days
where day.DayOfWeek == weekday
orderby day.Day ascending
select day;
return weekdays.Take(amounttoshow);
}
// returns the day in datetime
public static DateTime DayOfYear(DateTime dt, int day)
{
DateTime firstDayOfYear = new DateTime(dt.Year, 1, 1);
DateTime dateTime = firstDayOfYear.AddDays(dt.DayOfYear - 1 + day);
return dateTime;
}
To get a value
DateTime d = new DateTime(2011, 11, 5);
IEnumerable<DateTime> ie = ReturnNextNthWeekdaysOfMonth(d, DayOfWeek.Friday, 4);
System.Diagnostics.Debug.WriteLine(ie.First().ToString());
A higher-speed alternative (arithmetic instead of a search loop for the first date, and moving the expensive multiplication outside the loop):
public static IEnumerable<DateTime> ReturnNextNthWeekdaysOfMonth(DateTime dt,
DayOfWeek weekday, int amounttoshow = 4)
{
var day = dt.AddDays(weekday > dt.DayOfWeek
? weekday - dt.DayOfWeek
: 7 - weekday - dt.DayOfWeek);
var days = new List<DateTime>();
for(var until = day.AddDays(7 * amounttoshow);
day < until;
day = day.AddDays(7))
days.Add(day);
return days.ToArray();
}