Time Duration in VB.NET - vb.net

Trying to figure out time formatting is absolutely killing me.
When I press a button I collect a start time using:
StartTime = DateTime.Now.ToString("hh.mm.ss.tt")
Then when the calculation is done I have:
EndTime = DateTime.Now.ToString("hh.mm.ss.tt")
What I would like to do is to:
TotalTime = EndTime - StartTime
But to print the time using the format; "?# Hours, ## Minutes, & ## Seconds"

I probably wouldn't use the ToString() function on the StartTime and EndTime variables, since that turns them into strings.
Try this:
Dim StartTime as DateTime = DateTime.Now
'' Do Stuff
Dim EndTime As DateTime = DateTime.Now
Dim TotalTime As TimeSpan = EndTime - StartTime
Me.Text = TotalTime.ToString("hh':'mm':'ss")
Of course, you can skip the TotalTime variable and just calculate it in place:
Me.Text = (EndTime - StartTime).ToString("hh':'mm':'ss")

If you want to calculate durations, you must not use the string type. Use directly the DateTime variables (that is, DateTime.Now). You should get a TimeSpan object when subtracting.

Dim TotalTime As TimeSpan = EndTime - StartTime
Console.WriteLine( _
"{0:#0} Hours, {1:00} Minutes, & {2:00} Seconds", _
Math.Truncate(TotalTime.TotalHours), _
TotalTime.Minutes, _
TotalTime.Seconds _
)

Solution by OP.
LarsTech answer got me thinking about a better solution. I completely forgot that I had datetime.now.tostring. What I ended up going is:
timenow = DateTime.Now
start = DateTime.Now
Dim totaltime As TimeSpan = (timenow - start)
xlWorkSheet201.Cells(3, 9) = "Total Test Time: " & Format(totaltime.Hours, "#0") & " Hours, " & Format(totaltime.Minutes, "#0") & "Minutes, & " & Format(totaltime.Seconds, "00") & "Seconds."

Related

How to transfer Time format "hh:mm tt" from Datagridview data cell to a datetimepicker?

I tried to do the following:where StartTime EndTime are a Datetimepicker
StartTime.Value = "01/01/2010 " & DGVEvemts(1, DGVEvemts.Rows.Count - 1).ToString("hh:mm tt")
EndTime.Value = "01/01/2010 " & DGVEvemts(2, DGVEvemts.Rows.Count - 1).ToString("hh:mm tt")
You should not be using Strings at all. DO NOT convert between DateTime and String for any reason that doesn't involve requiring a String as an output, e.g. display or serialisation, or as an input, e.g. reading a file or user input at the console. If you are starting with a DateTime and you want to end with a DateTime then there should be no intermediate Strings involved.
Assuming that your DataGridView contains DateTime values, you can do this:
StartTime.Value = #1/01/2010# + CDate(DGVEvemts(1, DGVEvemts.Rows.Count - 1)).TimeOfDay
That creates a Date literal, gets the Date from the grid, gets the time portion from that Date and adds it to the literal. If the time in the grid might contain partial minutes and you only want whole minutes, you can do this:
Dim dt = CDate(DGVEvemts(1, DGVEvemts.Rows.Count - 1))
StartTime.Value = #1/01/2010# + New TimeSpan(dt.Hours, dt.Minutes, 0)
If DGVEvemts.Rows.Count < 1 Then Return
RecStTxt.Text = "01/01/2010 " & DGVEvemts(1, DGVEvemts.Rows.Count - 1).Value.ToString()
RecEndTxt.Text = "01/01/2010 " & DGVEvemts(2, DGVEvemts.Rows.Count - 1).Value.ToString()
StartTime.Value = RecStTxt.Text
EndTime.Value = RecEndTxt.Text

Simple Date Difference Referencing Form Control

I am trying to do a simple date difference calculation that returns a Year and Month value. The code the I have now is:
Private Sub Form_AfterUpdate()
Dim IntegerYears As Long
Dim IntegerMonths As Long
IntegerYears = DateDiff("yyyy", Me.DeemedFilingDate, Now())
IntegerMonths = DateDiff("m", Me.DeemedFilingDate - IntegerYears, Now())
Me.TimeElapsedFromFilingDate = IntegerYears & " Yr(s)." & " " & "," & " " & IntegerMonths & " Mo(s)."
End Sub
At this point, I am getting an output in year/month format, but it's not correct. I am getting negative numbers, the month count goes above 12 months, and the year shows 1 year when the start date is in the previous year but a year hasn't necessarily passed. For instance, the code will return 1 year if the start date is 12/1/2017 and the current date is 3/2/2018 instead of just returning 3 months.
You're doing multiple unusual things. Let me walk you through them:
You've declared TimeElapsed as a double, but you're setting it equal to the result of DateDiff, which returns a Variant(Long)
Dim TimeElapsed As Long
You need to use string delimiters in your DateDiff for the first argument. Also, it's lower case y, not upper case:
TimeElapsed = DateDiff("yyyy", Now(), Me.DeemedFilingDate)
This line:
IntegerMonths = Round(TimeElapsed - IntegerYears) * 12
Makes no sense to me. You're taking the time elapsed, removing the time difference between then and now in years, then rounding it, and then multiplying it by 12?
You probably want the following instead:
IntegerMonths = DateDiff("m", Now(), Me.DeemedFilingDate - TimeElapsed)
Also, VBA doesn't really do integers. All integers in VBA are really longs that get cast to an integer as needed. Using a long is more efficient, and doesn't take more memory.
Final result:
Private Sub Form_AfterUpdate()
Dim IntegerYears As Long
Dim IntegerMonths As Long
IntegerYears = DateDiff("yyyy", Now(), Me.DeemedFilingDate)
IntegerMonths = DateDiff("m", DateAdd("yyyy", IntegerYears *-1, Now()), Me.DeemedFilingDate)
Me.TimeElapsedFromFilingDate = IntegerYears & " Years " & IntegerMonths & " Months"
End Sub
Resolved:
Private Sub Form_AfterUpdate()
Dim TimeElapsedMonths As Integer
Dim TimeElapsedYears As Integer
Dim TimeElapsedRemMonths As Integer
TimeElapsedMonths = DateDiff("m", Me.DeemedFilingDate, Now())
TimeElapsedRemMonths = TimeElapsedMonths Mod 12
TimeElapsedYears = Int(TimeElapsedMonths / 12)
Me.TimeElapsedFromFilingDate = TimeElapsedYears & " Yr(s)." & "," & " " &
TimeElapsedRemMonths & " Mo(s)."
End Sub

How can I convert a long date with time to a different format in VBA?

I have data for a date that looks like this: "2015-02-11T19:41:50-08:00"
I would like to know if there is already a function that exists in VBA which can convert the above data to the format of something like "02/11/2015 11:41 AM PST"
I attempted the following code playing around with the format function but was unable to get VBA to recognize the format as a date:
testdate = "2015-02-12T22:57:05-08:00"
newdate = Format(testdate, "mm/dd/yyyy hh/nn/ss AM/PM")
Debug.Print newdate
The output was still "2015-02-12T22:57:05-08:00"
Thanks for the help.
Edit:
I was able to resolve the problem by taking your suggestions to use the mid() function since the dates are in fixed format. I decided to keep the military time in the final version.
Here is my code for anyone curious:
Function convertDate(orderdate)
'takes the date formatted as 2015-02-06T08:26:00-08:00
'and converts it to mm/dd/yyyy hh/nn/ss UTC format
'2015-02-06T08:26:00-08:00
orderyear = Mid(orderdate, 1, 4)
ordermonth = Mid(orderdate, 6, 2)
orderday = Mid(orderdate, 9, 2)
orderhour = Mid(orderdate, 12, 2)
orderminute = Mid(orderdate, 15, 2)
ordersecond = Mid(orderdate, 18, 2)
newdate = ordermonth & "/" & orderday & "/" & orderyear
newtime = orderhour & ":" & orderminute & ":" & ordersecond
'Debug.Print newdate
convertDate = newdate & " " & newtime & " UTC"
End Function
Because your input isn't a true date none of Excel or VBA's date methods will work with it. Your best bet is to break the string down into parts, work with them individually, and then join it all back up again - for example:
testdate = "2015-02-12T22:57:05-08:00"
'// The letter T is redundant, so let's split the string here into an array:
dateArr = Split(testdate, "T")
'// Part 1 of the array can be easily converted with CDate() and Format()
dateArr(0) = Format(CDate(dateArr(0)), "mm/dd/yyyy")
'// Part 2 of the array will need to be broken down further:
dateArr(1) = Format(TimeValue(Split(dateArr(1), "-")(0)) - _
TimeSerial(Left(Split(dateArr(1), "-")(1), 2), _
Right(Split(dateArr(1), "-")(1), 2), 0), "hh:mm:ss")
'// The above line does the following:
'// 1) Split the second part of the array again, using the "-" as the delimiter
'// 2) Convert the first part of this (22:57:05) to a time using TimeValue()
'// 3) Convert the second part (08:00) to hours & minutes using TimeSerial()
'// 4) Minus the latter from the former (which can only be done if both are a valid time)
'// 5) Wrap all that into a Format() method to show "hh:mm:ss" instead of a Double.
'// Join the two parts back together and add "PST" on the end.
newdate = Join(dateArr, " ") & " PST"
Debug.Print newdate
'// Output will display "02/12/2015 14:57:05 PST"
N.B. I have chosen not to include "AM" or "PM" because your time is in 24hr format anyway so I don't see the relevance...
It's not converting because of the "T" and because of the tacked on time range at the end. You can ditch the "T" and truncate off the trailing range and it will convert.
Public Sub Example()
Const testValue As String = "2015-02-12T22:57:05-08:00"
Dim dateValue As Date
Dim stringValue As String
Dim subVal As Date
Dim hyphenPos As Long
stringValue = testValue
Mid(stringValue, 11&, 1&) = " "
hyphenPos = InStrRev(stringValue, "-")
subVal = Mid$(stringValue, hyphenPos + 1&)
dateValue = CDate(Left$(stringValue, hyphenPos - 1&)) - subVal
End Sub
Couple of ideas:
The sample date you have 2015-02-12T22:57:05-08:00 is not a real date (I think)
I think the following will give you the closest format to what you are looking for (you will need to define the range.Range.NumberFormat = "[$-409]h:mm:ss AM/PM"
Your best bet is concating "PST" to a date datatype formatted to your needs.
Sub DebugPrintDate()
Dim testdate As Date: testdate = Now
newdate = Format(testdate, "mmm/dd/yyyy hh:mm AM/PM") & " PST"
Debug.Print newdate
End Sub
Ouput:
Never mind the "févr". My system locale is France.
If you want to define a particular date, make sure to wrap the date in two #s.
Example:
Dim someDateAndTime As Date = #8/13/2002 12:14 PM#

How to set only time part of a DateTime

I need to set datetime variable but it's time part must be 3:00:00 AM.
For example if i call getdate() now i'll get 1/20/2014 3:52:03 AM. I need to set it to 1/20/2014 3:00:00 AM.
Does anybody have a good snippet for that or any ideas how to do it right? would really appreciate some help.
The constructor for the DateTime allows you to specify hours, minutes and seconds as well as the usual day month and year.
Dim now As DateTime = DateTime.Now
Dim myDate = New DateTime(now.Year, now.Month, now.Day, 3, 0, 0, 0)
There are a lot of ways to do this - reading the documentation might give you more ideas
Dim someDate As DateTime = DateTime.Now()
Dim threeAmDate As DateTime = New DateTime(someDate.Year, _
someDate.Month, _
someDate.Day, _
3, _ 'hours
0, _ 'minutes
0, _ 'seconds
0) 'milliseconds
Console.WriteLine(threeAmDate)
try this
Label1.Text = DateAndTime.Today & " " & TimeOfDay
you can put this in a label or anything and you can change time of day to "3:00:00"
This one is old... But I came across having the same question.
Dim dt As New DateTime(_DateTo.Ticks + _TimeTo.Ticks)
--> Both '_DateTo' and/or '_TimeTo' could be Timespan or Datetime objects.

Calculating time difference in seconds

I am using following code to calculate time difference. I want to display it in seconds, not in HH:MM:SS
Please advise.
Dim myTime = DateTime.Parse("15:40:00 PM")
Dim vrNowTime = DateTime.Parse(TimeOfDay)
Dim result = vrNowTime - myTime
Label1.Text = vrNowTime & " " & myTime
MsgBox(result.ToString)
Thanks
Use result.TotalSeconds (and round it if you want an integer number to be displayed).
Also you may want to write simply:
Dim result as TimeSpan = Now() - myTime
You can also use
Dim Result = DateDiff(DateInterval.Second,Time1,Time2)