Domanda

I am having two date time picker start time and end time.I have to calculate difference between time from this end time and start time.And also how to check am or pm for calculating time difference.

I have tried this by using timespan. It gives me right answer,but when I select time suppose as 12:58:02 in end time and 10:57:05 in start time, it gives me wrong answer like -599. I want to know how to convert this negative difference to positive.

I have tried with the following code:

Dim startTime As Date
Dim endTime As Date
startTime = Convert.ToDateTime(dtpOpStTime.Value)
endTime = Convert.ToDateTime(dtpOpETime.Value)
Dim diff As System.TimeSpan
diff = endTime - startTime
actualTime = Convert.ToString(Int32.Parse(diff.Hours.ToString()) * 60 + Int32.Parse(diff.Minutes.ToString()))
ucTime.TxtCode.Text = actualTime

my another issue is as follows: I am having 4 date time picker,2 for showing start date and end date and 2 for start time and end time.so when i changed date timespan getting is wrong .so how to resolve this. I have tey with the following code:

Dim span As TimeSpan = dtpOpEDate.Value - dtpOpStdate.Value
                    Dim span1 As TimeSpan = dtpOpETime.Value - dtpOpStTime.Value
                    Dim duration As TimeSpan = span.Duration()
                    Dim duration1 As TimeSpan = span1.Duration()
                    Dim durDay As Int32 = duration.Days
                    Dim durHr As Int32 = duration1.Hours
                    Dim durMin As Int32 = duration1.Minutes
                    Dim totalDur = durDay * 24 * 60 + durHr * 60 + durMin
                    actualTime = totalDur.ToString()
                    ucTime.TxtCode.Text = actualTime

Problem is through this I am getting wrong time difference ,when i change suppose start time 10:51:02 PM and end time to 3:51:04 AM and start date to 25-Mar-2014 and End date to 26-Mar-2014 then difference should be 5 hours though the day change but i am getting wrong difference

È stato utile?

Soluzione

A difference between two DateTimes returns a TimeSpan object. You can either use the Subtract method of DateTime or even use -. You have to use the subtract the earlier date from the later date:

Dim span As TimeSpan = dtpEnd.Value - dtpStart.Value

You can use the Duration method to get an absolute timespan, then the order doesn't matter:

Dim duration As TimeSpan = (dtpStart.Value - dtpEnd.Value).Duration()

If you for example want the number of minutes between, use the TotalMinutes property:

Dim minutes As Int32 = CInt(duration.TotalMinutes)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top