I have two masked TextBox controls and was wondering how I\'d go about getting the time in each one and then converting the difference into milliseconds. Like, say in tb1 I
Many of the above mentioned solutions might suite different people.
I would like to suggest a slightly modified code than most accepted solution by "MusiGenesis".
DateTime firstTime = DateTime.Parse( TextBox1.Text );
DateTime secondTime = DateTime.Parse( TextBox2.Text );
double milDiff = secondTime.Subtract(firstTime).TotalMilliseconds;
Considerations:
- earlierTime.Subtract(laterTime)
you will get a negative value.
- use int milDiff = (int)DateTime.Now.Subtract(StartTime).TotalMilliseconds;
if you need integer value instead of double
- Same code can be used to get difference between two Date values and you may get .TotalDays
or .TotalHours
insteaf of .TotalMilliseconds
If you just want to display a message box at 12:02, use a timer control with delay of, say, 250ms, that keeps checking if the current time is 12:02. When it is, display the message and stop the timer. Note this does not require a start time field (although you may be using that for something else -- I don't know -- in which case the other code provided to you here will be helpful).
Try:
DateTime first;
DateTime second;
int milliSeconds = (int)((TimeSpan)(second - first)).TotalMilliseconds;
public static Int64 GetDifferencesBetweenTwoDate(DateTime newDate, DateTime oldDate, string type)
{
var span = newDate - oldDate;
switch (type)
{
case "tt": return (int)span.Ticks;
case "ms": return (int)span.TotalMilliseconds;
case "ss": return (int)span.TotalSeconds;
case "mm": return (int)span.TotalMinutes;
case "hh": return (int)span.TotalHours;
case "dd": return (int)span.TotalDays;
}
return 0;
}
DateTime dt1 = DateTime.Parse(maskedTextBox1.Text);
DateTime dt2 = DateTime.Parse(maskedTextBox2.Text);
TimeSpan span = dt2 - dt1;
int ms = (int)span.TotalMilliseconds;
If you are only dealing with Times and no dates you will want to only deal with TimeSpan and handle crossing over midnight.
TimeSpan time1 = ...; // assume TimeOfDay
TimeSpan time2 = ...; // assume TimeOfDay
TimeSpan diffTime = time2 - time1;
if (time2 < time1) // crosses over midnight
diffTime += TimeSpan.FromTicks(TimeSpan.TicksPerDay);
int totalMilliSeconds = (int)diffTime.TotalMilliseconds;