C# Display time intervals in dropdown - c#

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.

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

C# Group by each month

Here's a code.
decimal[] men;
for (b.Pradzia();b.Yra();b.Kitas()) // loops through editions
{
men = new decimal[13]; //
for (a.Pradzia();a.Yra();a.Kitas()) // loops through subscribers
{
if (b.ImtiDuomenisL().Kodas == a.ImtiDuomenisP().Kodas) // if edition code matches subscriber code proceed
{
int j = a.ImtiDuomenisP().LaikotarpioPradžia + a.ImtiDuomenisP().LaikotarpioIlgis; // gets the start of subscription +
// the lenght of it.
for (int i = a.ImtiDuomenisP().LaikotarpioPradžia; i <= j; i++)
{
Dictionary<Leidinys, decimal> suma = new Dictionary<Leidinys, decimal>();
if (j <= 12)
{
men[i] += a.ImtiDuomenisP().Kiekis * b.ImtiDuomenisL().Kaina;
}
else
{
men[j - 12] += a.ImtiDuomenisP().Kiekis * b.ImtiDuomenisL().Kaina;
}
suma.Add(b.ImtiDuomenisL(), men[i]); // adds the edition and the sum of it to the dictionary.
}
}
}
}
What I get from this method is the sum of each edition in each month. Months are in integers for reasons.
For each month I need to determine, which edition got most money. I do not know how.
Assuming your "j" variable is months (Your code is a bit confused) you just need something like this:
int moneyofmonth = 0;
int biggest = 0;
foreach(var month in j)
{
moneyofmonth = //moneyofthismonth using the var "month".
if(moneyofmonth > biggest)
{
biggest = moneyofmonth;
}
}
"biggest" will be the biggest money of all months. If you want so save the month of the biggest, it's just to make a new var inside if saving the "month" variable.

Automatic Day Assign

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
}

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# loops through 24 hours every 30 minutes

I am wondering how I would loop through a datetime or any type of variable to go from 12:00AM to 11:59PM every 30 Mins?
So I need a variable that shows times in 12HR format (01:00PM, 09:00AM) and everytime I loop through it, to add 30 mins to the time? I then need to use this value in a string.
The time needs to start at 10:00AM
And there is always LINQ
var start = DateTime.Today;
var clockQuery = from offset in Enumerable.Range(0, 48)
select start.AddMinutes(30 * offset);
foreach (var time in clockQuery)
Console.WriteLine(time.ToString("hh:mm tt"));
... LINQ + FUNC (for parameterized start)
Func<DateTime, IEnumerable<DateTime>> clockQuery = start =>
from offset in Enumerable.Range(0, 48)
select start.AddMinutes(30 * offset);
foreach (var time in clockQuery(DateTime.Today))
Console.WriteLine(time.ToString("hh:mm tt"));
... or if you just want the TimeSpan offsets ...
var start = DateTime.Today;
var clockQuery = from offset in Enumerable.Range(0, 48)
select TimeSpan.FromMinutes(30 * offset);
foreach (var time in clockQuery)
Console.WriteLine((start + time).ToString("hh:mm tt"));
You could use an extension method:
public static class DateTimeHelper
{
public static IEnumerable<DateTime> GetHalfHours(this DateTime dt)
{
TimeSpan ts = TimeSpan.FromMinutes(30);
DateTime time = dt;
while(true)
{
yield return time;
time.Add(ts);
}
}
}
something like this?
DateTime timeloop = new DateTime(0);
timeloop = timeloop.Add(new TimeSpan(10, 00, 0)); //start at 10:00 AM
for (int i = 0; i < 48; i++)
{
string time =timeloop.ToString("hh:mm tt"); //print it as 1:30 PM
timeloop = timeloop.Add(new TimeSpan(0, 30, 0)); //add 30 minutes
}
DateTime can do simple arithmetic:
DateTime time = DateTime.Now;
time = time + TimeSpan.FromMinutes(1);
Causes time to be incremented by one minute.
You can use a Timer class and increase the DateTime by whatever amount of time is appropriate once per tick. If exactness is important here there are other, more appropriate timer classes.
There are other static methods on the TimeSpan class as well!
var times = new List<string>();
DateTime today = DateTime.Today;
DateTime tomorrow = today.AddDays(1);
for (var i = today; i < tomorrow; i = i.AddMinutes(30))
{
times.Add(i.ToShortTimeString());
}
DateTime time = new DateTime(2011,02,22,10,0,0);
List<String> times = new List<string>();
for (int i = 0; i < 48; i++)
{
time = time.AddMinutes(30);
times.Add(time.ToString());
}
This might do what you need
Something like this should work for you:
int workCount = 0;
var timer = new System.Timers.Timer(1800000); // every half hour
timer.AutoReset = true;
timer.Elapsed += (src, e) =>
{
Console.WriteLine(DateTime.Now.ToString("HH:mm:ss"));
if(++workCount == 48)
{
timer.Stop();
}
};
timer.Start();
DateTime endDate = DateTime.Now;
DateTime startDate = endDate.AddDays(-1);
while (startDate.AddMinutes(30) <= endDate)
{
string sdate = startDate.ToString("yyyy-MM-dd HH:mm");
string edate = startDate.AddMinutes(29).ToString("yyyy-MM-dd HH:mm");
string display = string.Format("{0} - {1}", sdate, edate);
Console.WriteLine(display);
startDate = startDate.AddMinutes(30);
}

Categories