I have a for loop in date time how ever counter doesn't increase. I didn't see the reason. Can you help me on it?
private void ubGO_Click(object sender, EventArgs e)
{
DateTime startDate = udteMin.DateTime.Date;
DateTime endDate = udteMax.DateTime.Date;
for (DateTime counter = startDate; counter <= endDate; counter.AddDays(1))
{
MessageBox.Show(counter.Date.ToString() + " " + counter.AddDays(1).Date.ToString());
}
}
AddDays returns a new DateTime object. It doesn't mutate your existing one. You'll need to reassign counter with the result of AddDays
counter = counter.AddDays(1);
Related
This code is now in the form1 constructor.
if (filesRadar.Length > 0)
{
for (int i = 0; i < filesRadar.Length; i++)
{
label2.Text = dates[i].ToString("ddd, dd MMM yyy HH':'mm");
}
}
I want to display the strings in dates when calling a method or something in the constructor and also in other places like when downloading finished. each time calling a method or enabling timer to display the strings in a loop in specific speed.
Now it's displaying but too fast then in the end displaying the last item only and it's not in loop.
or enabling timer to display the strings in a loop in specific speed.
What's keeping you from doing that?...
Drop the timer on your form and set its Interval property to something reasonable. For instance, an interval of 1000 would mean it changes every second. Make sure the Timer is turned on (Enabled).
Now move the i variable out to class level and get rid of the for loop:
private int i = -1;
private void timer1_Tick(object sender, EventArgs e)
{
if (filesRadar.Length > 0)
{
i++;
if (i >= filesRadar.Length)
{
i = 0;
}
label2.Text = dates[i].ToString("ddd, dd MMM yyy HH':'mm");
}
else
{
label2.Text = ""; // optional?
}
}
You do not need the if-statement, because the loop will only execute if there are items in the array:
for (int i = 0; i < filesRadar.Length; i++)
{
label2.Text += dates[i].ToString("ddd, dd MMM yyy HH':'mm") + Enviroment.NewLine;
}
You can make this as a void method and you can call whenever you want to:
public void ReportTime()
{
for (int i = 0; i < filesRadar.Length; i++)
label2.Text += dates[i].ToString("ddd, dd MMM yyy HH':'mm") + Environment.NewLine;
}
I've got list of DateTime objects that I need to check if they are a coherent time period.
How is this done?
There might be time gaps that I need to detect and act upon.
Edit:
From what I can see the DateTime objects are sorted.
I've got a TrackerObj class and Entry class the relevant however is only the timestamp in DateTime that each tracker holds:
public class TrackerObj
{
private DateTime timeStamp;
private string trackerId;
private int voltage;
public TrackerObj(string trackerId, DateTime timeStamp, int voltage)
{
this.trackerId = trackerId;
this.timeStamp = timeStamp;
this.voltage = voltage;
}
}
The only relevant here is the timeStamp that from data I've seen are sorted.
Edit: The list is a List each object on that list contains a DateTime timeStamp. In order to determine if the periods between the DateTime are "coherent".
My definition of coherent time:
A period of time where each timestamp are after the other, without gaps (breaks in time).
DateTime format:
mm-dd-yyyy hours:minutes:seconds
private bool arePeriodsCoherent(List<TrackerObj> list)
{
// determine if all the objects on this list are without gaps. Return true if this is true. else return false.
for(int i=0; i < list.Count; i++)
{
if(list[i].timeStamp > list[i + 1].timeStamp || list[i].timeStamp == list[i + 1].timeStamp)
{return false;}
else
{return true;}
}
}
What variations does posible timeStamps contain? Will I the above code fail to catch all scenarios?
This will find any endpoints in a coherent timeperiod:
private List<int> getTimeGapIndexEndPoints(double maxTimeGapSeconds)
{
int x = 1;
List<int> timeLapsIndexes = new List<int>();
for (int i = 0; i < trackerData[trackerId].currentList.Count(); i++)
{
if (x < trackerData[trackerId].currentList.Count())
{
DateTime t1 = trackerData[trackerId].currentList[i].TimeStamp;
DateTime t2 = trackerData[trackerId].currentList[x++].TimeStamp;
TimeSpan duration = t2.Subtract(t1);
if (duration.TotalSeconds > maxTimeGapSeconds)
{
// MessageBoxResult resultb = System.Windows.MessageBox.Show(this, "After index: "+i+" "+duration+" Duration for trackerId: " + trackerId + " exceed " + maxTimeGapSeconds);
timeLapsIndexes.Add(i);
}
}
}
return timeLapsIndexes;
//for (int j = 0; j < timeLapsIndexes.Count(); j++)
//{
// MessageBoxResult resultNumbers = System.Windows.MessageBox.Show(this, "After Index (i+1): " + timeLapsIndexes[j] + " for trackerId: " + trackerId);
//}
}
Have a great day everyone. :)
This question already has answers here:
date difference using datepicker in wpf
(2 answers)
Closed 8 years ago.
I want to calculate the differences between two dates, one picked form dateTimePicker1 and the other one 20 February of 2014 and store it in a string to added to my array and be able to display it in another form
THIS is my code:
TimeSpan getDateDifference(DateTime date1, DateTime date2)
{
TimeSpan ts = date1 - date2;
int differenceInDays = ts.Days;
string differenceAsString = differenceInDays.ToString();
return ts;
}
public class Patient
{
public string patientidString;
public string firstNameString;
public string lastNameString;
public string dateString;
public string differenceAsString;
public Patient()
{
patientidString = "";
firstNameString = "";
lastNameString = "";
dateString = "";
}
}
//Array
Patient[] patientInfo = new Patient[10];
private void button1_Click(object sender, EventArgs e)
{
TimeSpan difference = getDateDifference(new DateTime(2014, 2, 20), dateTimePicker1.Value);
if (textBox1.Text.Length == 0 || textBox2.Text.Length == 0 || textBox3.Text.Length == 0)
{
MessageBox.Show(" Patient id, first name and last name cannot be empty");
}
else
try
{
foreach (Patient patientinfoIndex in patientInfo)
patientInfo[itemCountInteger].patientidString = textBox1.Text;
patientInfo[itemCountInteger].firstNameString = textBox2.Text;
patientInfo[itemCountInteger].lastNameString = textBox3.Text;
patientInfo[itemCountInteger].dateString = dateTimePicker1.Text;
string names = patientInfo[itemCountInteger].patientidString + " " + patientInfo[itemCountInteger].firstNameString + " " + patientInfo[itemCountInteger].lastNameString;
listBox1.Items.Add(names);
itemCountInteger++;
listBox1.SelectedItem = names;
}
catch
{
MessageBox.Show("Contacts are limited to 20. Please delete some contacts prior to adding more.");
}
}
//Search Button search a patients name and display his surname in the label if patient is found display his surname
private void button2_Click(object sender, EventArgs e)
{
int intTest = 0;
for (int x = 0; x < patientInfo.Length; x++)
{
if (textBox4.Text == patientInfo[x].patientidString)
{
label6.Text = (patientInfo[x].firstNameString + " " + patientInfo[x].lastNameString);
PatientForm patientform = new PatientForm();
patientform.Show();
patientform.label6.Text = (patientInfo[x].patientidString);
patientform.label7.Text = (patientInfo[x].firstNameString);
patientform.label8.Text =(patientInfo[x].lastNameString);
patientform.dateTimePicker1.Text = (patientInfo[x].dateString);
patientform.label9.Text = (patientInfo[x].differenceAsString);
intTest = 1;
break;
}
}
if (intTest == 0)
{
label6.Text = ("not found");
}
}
DateTime febDate = new DateTime(2014, 2, 20);
DateTime pickerDate = myDateTimePicker.Value;
TimeSpan tspan = febDate - pickerDate;
int differenceInDays = tspan.Days;
string differenceAsString = differenceInDays.ToString();
If differenceInDays < 0 then multiply it by -1.
Note: In this case it's very easy to get the difference in hours, minutes or seconds as well.
Here's an example of the above code in it's own method:
TimeSpan getDateDifference(DateTime date1, DateTime date2)
{
TimeSpan ts = date1 - date2;
return ts;
}
And when you want to trigger this method:
TimeSpan difference = getDateDifference(new DateTime(2014, 2, 20), dateTimePicker.Value);
//Now you can do what you want with the TimeSpan.
int differenceInDays = difference.Days;
int differenceInHours = difference.Hours;
Console.WriteLine(differenceInDays.ToString());
DateTime a = new DateTime.Parse(string);
Console.WriteLine(datePicker.Value.Subtract(a).TotalMinutes);
You can subtract any two dates and it will work.
DateTime date1 = new DateTime(2014,02,20);
DateTime date2 = dateTimePicker1.Value as DateTime;
TimeSpan difference = date1 - date2; //dunno what difference you need so you can swap these
This is the code I have at the moment:
String getDayRequested;
public void setDay(String getDayFromForm1)
{
getDayRequested = getDayFromForm1;
{
if (getDayRequested.Contains("today"))
{
getDayRequested = DateTime.Today.DayOfWeek.ToString();
}
else if (getDayRequested.Contains("tomorrow"))
{
getDayRequested = DateTime.Today.AddDays(1).DayOfWeek.ToString();
}
}
This checks my TextBox.Text string from Form1, and checks to see if the text "today" or "tomorrow" is in it.
Can anyone help me in the right direction of how to check the string for information asked about upcoming days; ie: "What will be the date this saturday", and add the appropriate number of days depending on what the day is when asked.
UPDATE
Using the code in the accepted answer, I used the following in my above else if statement to complete what I was after:
else if (getDayRequested.Contains("monday"))
{
getDayRequested = GetFutureDay(DateTime.Now, DayOfWeek.Monday).ToString("dd");
}
This handy little method will return a future day of the week.
public DateTime GetFutureDay(DateTime start, DayOfWeek day)
{
int daysToAdd = (day - start.DayOfWeek + 7) % 7;
return start.AddDays(daysToAdd);
}
It would be called like:
var day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), getDayFromForm1);
var getDayRequested = GetFutureDay(DateTime.Now, day);
Consider the following snippet of code...
DateTime date;
public void setDay(String day)
{
DayOfWeek futureDay = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), day);
int futureDayValue = (int)futureDay;
int currentDayValue = (int)DateTime.Now.DayOfWeek;
int dayDiff = futureDayValue - currentDayValue;
if (dayDiff > 0)
{
date = DateTime.Now.AddDays(dayDiff);
}
else
{
date = DateTime.Now.AddDays(dayDiff + 7);
}
}
Good Luck!
I have a small C# program that has a calendar and 7 labels. When I select a date the labels display the days and dates of that week.
The labels are populated using the TimeSpan string what I want to do is format this string so that it only displays the days and dates with out the times.
This is the code I have so far:
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
DateTime dTime = new DateTime();
dTime = monthCalendar1.SelectionStart;
dTime -= new TimeSpan((int)dTime.DayOfWeek, 0, 0, 0 );
for (int i = 1; i < 8; i++)
{
var dt = dTime.AddDays(i);
lb[i].Text = dt.DayOfWeek + " : " + dt.Date;
}
}
You can call dt.Date.ToShortDateString().
You have multiple options.
You can use ToShortDateString() method for the DateTime type
lb[i].Text = dt.DayOfWeek + " : " + dt.Date.ToShortDateString()
or you can provide of a format to the ToString("format") method to specify exactly what you want it to look like.
lb[i].Text = dt.DayOfWeek + " : " + dt.Date.ToString("MM/dd/yyyy");
Try with DateTime.ToShortDateString() method;
Converts the value of the current DateTime object to its equivalent
short date string representation.
DateTime dt = DateTime.Now;
label8.Text = dt.Date.ToShortDateString());
You can learn more details from Custom Date and Time Format Strings