Automatic Day Assign - c#

I need help about assigning day automatically. I couldn't find correct way.
Now problem is that I have fitness program. And I will add new user. When I add I will add program too. Fitness program has limit.
For example. 8 seans. Then user chooses every Saturday and Sunday.
16.03.2019, 17.03.2019, 23.03.2019, 24.03.2019,
30.03.2019, 31.03.2019, 06.04.2019, 07.04.2019
The dates will be assign automatically due to his chosen. uye.DAYS choosed days of week. For example '0,6' and uye.SURE means limit of seans
if(uy.UYELIK== "PLATES")
{
DateTime date = DateTime.Now.Date;
System.TimeSpan duration = new System.TimeSpan(1, 0, 0, 0);
for (int i = 0; i < uye.SURE; i++)
{
date = date.Add(duration);
var list = uye.DAYS.Split(',');
for(int j = 0; j < list.Length; j++)
{
if ((int)date.DayOfWeek == Convert.ToInt32(list[j]))
{
HR_FITNESS_USER_PLATES_PROGRAM program = new HR_FITNESS_USER_PLATES_PROGRAM();
program.REF_HOCA = uye.HOCA;program.SEANS_LIMIT = uye.SURE;program.SEANS_TIME = date;program.REF_UYELIK = uy.ID;program.SICIL = uye.SICIL.ToString();
db.HR_FITNESS_USER_PLATES_PROGRAM.Add(program);db.SaveChanges();
}
}
}
}
This code is not correct. Here I can't increase day if not one of them. How can I do it?

As I understand, you need to insert a weekend fitness program for a member. Here is a simple psuedocode for that,
var startDate = DateTime.Today; //today
int currentDayOfWeek = (int)startDate.DayOfWeek; //today
//saturday of this week, disregarding if today is
//saturday or sunday, it is up to you to enhance this.
DateTime thisSaturday = startDate.AddDays(6 - currentDayOfWeek);
var sessions = 8;
for (int i = 0; i<sessions; i++)
{
SaveToDb(thisSaturday);
thisSaturday = thisSaturday.AddDays(7); //next week's weekend
}
private void SaveToDb(DateTime saturday)
{
DateTime sunday = saturday.AddDays(1);
//insert data for saturday and sunday
}

Related

How to find the EndDate from a set of given inputs

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

Calculate the Number of Mondays in a Month

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 set of dates in a specific week ,given the month and the year?

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 ##

How to display current date by default on drop down list?

I would like to display a week of dates with the default being today's date on a drop down list. How can I do this?
I was also told to "use class DateTime.Now, and convert the data value into a string".
Any help is appreciated!
this works for me on my asp.net project
DropDownList1.Items.Add(DateTime.Now.ToString());
and this one on my combobox
comboBox1.Items.Add(DateTime.Now);
i'm not entirely sure about your question. is the following you want to do?
for (int i = 0; i < 7; i++)
{
DropDownList1.Items.Add(DateTime.Now.AddDays(-i).ToString());
}
Try This:
//Get Start And End
int delta = Convert.ToInt32(DateTime.Now.DayOfWeek);
delta = delta == 0 ? delta + 7 : delta;
DateTime moday = DateTime.Now.AddDays(1 - delta);
DateTime sunday = DateTime.Now.AddDays(7 - delta);
//Get Date Range
List<DateTime> allDates = new List<DateTime>();
//Add To Your List
for (DateTime i = moday; i <= sunday; i = i.AddDays(1))
{
DropDownList1.Items.Add(i.Date.DayOfWeek);
}
//Select Today Name
DropDownList1.SelectedItem = DateTime.Today.Date.DayOfWeek;
Edited
For This Format(mm/dd/yyy)
//Add To Your List
for (DateTime i = moday; i <= sunday; i = i.AddDays(1))
{
comboBox1.Items.Add(i.Date.ToShortDateString());
}
//Select Today Date(dd/mm/yyy)
comboBox1.SelectedItem = DateTime.Today.ToShortDateString();
you can put it on the load event
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 7; i++)
{
DropDownList1.Items.Add(DateTime.Now.AddDays(-i).ToString());
}
}

C# Display time intervals in dropdown

Having derived this logic to bind dropdownlist to set of time intervals, I would like to get this improved in terms
Use native data types designed to date and time
Make it configurable
pseudocode
for (var hoursCount = 0; hoursCount <= 12; i++) {
for (var timeSlots = 0; timeSlots < 2; j++) {
string hourAndMinute = hoursCount;
if (timeSlots == 0) {
hourAndMinute += ":00 AM";
} else {
hourAndMinute += ":30 AM";
}
if (hourAndMinute != "12:00 AM" || hourAndMinute != "12:30 AM") {
alert(hourAndMinute);
}
}
}
Output
0:00 AM
0:30 AM
.
.
.
12:30 AM
It's unclear what sort of "configuration" you want here, but as you're only dealing with a time, I would personally use Noda Time which has the LocalTime struct for handling this sort of thing. (Disclaimer: I'm the main developer on Noda Time, so I'm somewhat biased.) You could just use DateTime, but as you don't want a date...
It's not really clear what kind of "configuration" you want, but in Noda Time you could write:
LocalTimePattern pattern = LocalTimePattern.CreateWithInvariantInfo("hh:mm tt");
for (var hour = 0; hour <= 12; hour++) {
for (var slot = 0; slot < 2; slot++) {
LocalTime time = new LocalTime(hour, slot * 30, 0);
Console.WriteLine(pattern.Format(time));
}
}
With more details of what you want to do, we can no doubt help more.
EDIT: Okay, it sounds like maybe you want something like:
static void DisplaySlots(string format, Period slotLength, int slots)
{
// Or change the parameter to be a LocalTimePattern
LocalTimePattern pattern = LocalTimePattern.CreateWithInvariantInfo(format);
LocalTime time = LocalTime.Midnight;
for (int i = 0; i < slots; i++)
{
Console.WriteLine(pattern.Format(time));
time = time + slotLength;
}
}
Then call it with:
DisplaySlots("HH:mm", Period.FromMinutes(20), 100);
(Or whatever...)
Alternative using DateTime:
static void DisplaySlots(string format, TimeSpan slotLength, int slots)
{
DateTime time = DateTime.Today;
for (int i = 0; i < slots; i++)
{
Console.WriteLine(time.ToString(format));
time = time + slotLength;
}
}
Use DateTime struct at first for the logic and then convert it to string with preferred format to display.

Categories