how to calculate time using vb.net
I make a project car rentals but I have trouble counting time, to take the penalty when you return the car late, please help me
this is my code
Dim date1 As DateTime
Dim date2 As DateTime
'DateTimePicker1 = today's date 10/07/2011 11:10
'DateTimePicker2 = date back 10/07/2011 09:00
date1 = Convert.ToDateTime (Me.DateTimePicker2.Value)
date2 开发者_JAVA百科= Convert.ToDateTime (Me.DateTimePicker1.Value)
Dim diff As System.TimeSpan
diff = date2 - date1
Me.txtresult.text = diff.Hours & diff.Minutes
but the results do not correspond..
I want the result = 2 hours 10 minutes
someone help me,,, please ....
For the case of 2 hours and 10 minutes, diff.Hours & diff.Minutes
returns 210
, because &
concatenates the string representations of the numbers 2
and 10
. To format the string the way you want, use String.Format()
:
String.Format("{0} hours {1} minutes", diff.Hours, diff.Minutes)
This is going to show unexpected results when the time is over one day. For example, 25 hours and 5 minutes would show as “1 hours 5 minutes”. To fix that, you either need to check the value of diff.Days
or use diff.TotalHours
.
assuming i read your question correctly, since date1 > date2
, then you will need to use:
Dim diff = date1 - date2
otherwise you'll get back -2 hours and -10 minutes... :)
Subtract the earlier date from later date (note DateTime has a Subtract method if you like). Also, remember to account for days. To illustrate the concept, the following shows five ways to express approximately the same time span.
Note that the TimeSpan member properties like Days, Hours, Minutes, etc, represent the respective integral part of the time span (i.e., Hours = 0 - 23, Minutes = 0 - 59) whereas the members like TotalHours, TotalMinutes, etc, are representative of the whole span. Hence this is why they are doubles...
'Assuming DateTimePicker1 has the earlier date...
Dim date1 As DateTime = Me.DateTimePicker1.Value
'Assuming DateTimePicker2 has the later date...
Dim date2 As DateTime = Me.DateTimePicker2.Value
'Get the difference (TimeSpan)...
Dim diff As System.TimeSpan = date2.Subtract(date1)
'Some different ways to express the resulting TimeSpan...
Console.WriteLine(String.Format("{0} days, {1} hrs, {2} min, {3} sec", diff.Days, diff.Hours, diff.Minutes, diff.Seconds))
Console.WriteLine("total days = " & diff.TotalDays)
Console.WriteLine("total hours = " & diff.TotalHours)
Console.WriteLine("total minutes = " & diff.TotalMinutes)
Console.WriteLine("total seconds = " & diff.TotalSeconds)
When you are parse strings with different date formats, you should specify what the format is:
date1 = DateTime.ParseExact(Me.txttanggalkembali.Value, "dd'/'MM'/'yyyy HH':'mm", CultureInfo.InvariantCulture)
date2 = DateTime.ParseExact(Me.DateTimePicker1.Value, "MM'.'dd'.'yyyy HH':'mm", CultureInfo.InvariantCulture)
You just need to use the TotalHours and TotalMinutes properties instead.
精彩评论