Time Interval in C#
Time Interval in C#
Details: Time Interval in C#
In this post, we will explore how to use the TimeSpan properties for finding the time interval. This separates every part of the time including, the hours, minutes, seconds, and milliseconds.
1 – To begin, we first start by creating a Windows Form Application in C# using Microsoft Visual Studio by following the steps:
– Navigate to File
– Click on New Project
– Select Windows Application
– Name Application TimeInterval.
2 – Proceed to add;
– DateTimePicker named dtpstrTime: for starting time
– Another DateTimePicker named dtpEndTime: to end the time.
Add 5 textboxes;
– txthours for displaying hours
– txtminutes for displaying minutes
– txtseconds to show seconds
– txtmillisecond to show milliseconds
– and txtticks to display ticks.
Insert a Button labelled btnGo. Your interface should look like the image below.
3 – Create a sub-procedure labelled TimeInterval used for separating the time interval of the corresponding fields. Copy and paste the code below:
private void TimeInterval(TimeSpan ts)
{
//use the properties of the timespan and it demonstrate timespan.hours
//, timespan.milliseconds , timespan.minutes , timespan.seconds
// and timespan.ticks
try
{
txthours.Text = ts.Hours.ToString();
txtmillisecond.Text = ts.Milliseconds.ToString();
txtminutes.Text = ts.Minutes.ToString();
txtseconds.Text = ts.Seconds.ToString();
txtticks.Text = ts.Ticks.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, this.Text);
}
}
4 – Use the code below for btnGo to get the time interval.
public void btngo_Click(System.Object sender, System.EventArgs e)
{
try
{
//create a variable of a timespan
TimeSpan time_span = new TimeSpan();
//create the variable of a datetime
DateTime strt_Date = default(DateTime);
DateTime end_Date = default(DateTime);
//set and convert the time from the datetimepicker
strt_Date = DateTime.Parse(dtpstrTime.Text);
end_Date = DateTime.Parse(dtpEndtime.Text);
//subtract the starting time and the end time
time_span = end_Date.Subtract(strt_Date).Duration();
//perform the sub procedure that you have
//created in displaying the time interval
TimeInterval(time_span);
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message, this.Text);
}
}
5 – Proceed to use the code below in the Form_Load.
public void Form1_Load(System.Object sender, System.EventArgs e)
{
//set the value of the end date higher than the start date
dtpEndtime.Value = DateAndTime.DateAdd(DateInterval.Hour, 9, dtpEndtime.Value);
dtpEndtime.Value = DateAndTime.DateAdd(DateInterval.Minute, 30, dtpEndtime.Value);
dtpEndtime.Value = DateAndTime.DateAdd(DateInterval.Second, 30, dtpEndtime.Value);
}