[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 196
  • Last Modified:

Add seconds to Time

I have a Time in a textbox as hhmmss.  I need to add some seconds to the time and have the result as hhmmss.

The following code almost works.  Can someone help me with the almost part.  <Grin>

I need a lot better solution than where I'm heading with this. The math seems to work, but the output format does not keep the hhmmss format.  It suppresses leading zeros, or if it should be 000045, my output shows 45.
Times are never more than 18 hours apart, so the general code flow is OK.


Private Sub Command1_Click()
   
    txtDifference.Text = CStr(AddSecToTime(txtStart.Text, txtStop.Text))
   
End Sub

Private Function AddSecToTime(Time1 As String, Seconds As Long) As Long

    Dim tm1 As Long
    Dim TimeInSec As Long
    Dim Hours As Long
    Dim Minutes As Long
    Dim TimeInSec As Long
   
    tm1 = 3600 * CLng(Mid(Time1, 1, 2)) + 60 * CLng(Mid(Time1, 3, 2)) _
       + CLng(Mid(Time1, 5, 2))
       
    TimeInSec = tm1 + Seconds
   
    If TimeInSec > 86400 Then
        TimeInSec = TimeInSec - 86400
    End If
   
    Hours = Int(TimeInSec / 3600)
    TimeInSec = TimeInSec Mod 3600
   
    Minutes = Int(TimeInSec / 60)
    TimeInSec = TimeInSec Mod 60
   
    AddSecToTime = Hours & Minutes & TimeInSec

End Function
0
MitchSavage
Asked:
MitchSavage
  • 3
1 Solution
 
ianouiiCommented:
u can't have leading zero bcoz your datatype is long instead of string. in this case,

just amend something in your code, hope it helps.

Private Function AddSecToTime(Time1 As String, Seconds As Long) As string

....
....  

AddSecToTime = cstr(Hours) & cstr(Minutes) & cstr(TimeInSec)

good luck.


0
 
ianouiiCommented:
then use a function called format.

format(cstr((TimeInSec, "0000000"))

good luck.
0
 
Ryan ChongCommented:
Hi, for the time value in txtStart & txtStop, i suggest you and a ":" between those value, look nicer, then you can use Split function to get the value of time in an array.

Alternatively, you can use TimeValue, TimeSerial function to do it, i think its much easier.
0
 
MitchSavageAuthor Commented:
ianouii,

Thanks, it works great now,  You got the almost out of my "It almost works".

Both of your suggestions were required to make it work.  .... As String.....    and Format(cstr........

Thanks again and
Best Regards,

Mitch
0
 
ianouiiCommented:
u're welcomed & thanks for your good grade. happy coding then. cheers!
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now