Results 1 to 24 of 24

Thread: Adding Time mm:ss

  1. #1

    Thread Starter
    Member
    Join Date
    Jun 2010
    Posts
    51

    Adding Time mm:ss

    Hello,

    I have string array of times arrtime(25) that holds time values (mm:ss)

    I would like to add all these times together and display in the format of mm:ss

    I tried to find an example, and I understand I need a TimeSpan object because once all the addition is done mm will be above 60. I understand that I will have to parse the data in the array. But after that I got lost when the examples I was looking at starting talking about cultures and other things above my head that are more advanced than what I am looking for.

    Any help is appreciated in devising a simple method to add the times.

    Thank you.

  2. #2
    PowerPoster
    Join Date
    Nov 2017
    Posts
    2,891

    Re: Adding Time mm:ss

    Quote Originally Posted by blaknite View Post
    I have string array of times arrtime(25) that holds time values (mm:ss)
    Where are these values coming from? Are you taking numeric time values and formatting them and then storing them as a string? If so, then don't do that, just keep them as numeric from the get go and then adding them up requires no extra anything.

  3. #3
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,684

    Re: Adding Time mm:ss

    Something like this should work.

    Code:
            Dim arrtime() As String = {"6:12", "4:15", "10:33"}
            Dim accum As TimeSpan = TimeSpan.FromTicks(0)
            For Each tmval As String In arrtime
                accum = accum.Add(TimeSpan.Parse("00:" & tmval))
            Next
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  4. #4

    Thread Starter
    Member
    Join Date
    Jun 2010
    Posts
    51

    Re: Adding Time mm:ss

    Quote Originally Posted by OptionBase1 View Post
    Where are these values coming from? Are you taking numeric time values and formatting them and then storing them as a string? If so, then don't do that, just keep them as numeric from the get go and then adding them up requires no extra anything.
    I will be importing the values from a text file. Each line has a time value for example the first line has a value of 1:37 and the next has a value of 10:36

    So I thought it made sense to import it as a string rather than a DateTime object. So then I needed to figure out how to keep it the way it was and then do the addition I wanted to do.

  5. #5
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,616

    Re: Adding Time mm:ss

    I would suggest going to the DateTime simply for convenience. Doing that addition is certainly possible without using TimeSpans, but TimeSpans are going to be quite a bit simpler. However, it might matter quite a bit what you will do with it in the end. After all, you are talking only about minutes and seconds, in which case you might be only interested in a sum, in which case the TimeSpan will actually work against you.

    If all you really want is the sum, then I would suggest turning the time into an integer count of seconds. For example, if the strings are "MM:SS", you might Split on ":", take the resulting array(0) * 60 + array(1) (converting both array(0) and array(1) to integers first, of course). Then you would just be summing total seconds. From that, if you want minutes, then integer divide by 60.

    That would assume that you don't care about the minutes and seconds as time, but just as a count. A TimeSpan will want those minutes and seconds to be time, and time has hours.
    My usual boring signature: Nothing

  6. #6
    Smooth Moperator techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,383

    Re: Adding Time mm:ss

    Quote Originally Posted by Shaggy Hiker View Post
    IAfter all, you are talking only about minutes and seconds, in which case you might be only interested in a sum, in which case the TimeSpan will actually work against you.
    How's that? I've used TimeSpan before to sum up things... and it works just fine... you can get .Minutes which would be Minutes mod 60 or you can get .TotalMinutes which will return the raw number of minutes regardless of hours.

    So if TotalMinutes = 76
    Minutes = 16
    Hours = 1


    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  7. #7

    Thread Starter
    Member
    Join Date
    Jun 2010
    Posts
    51

    Re: Adding Time mm:ss

    Quote Originally Posted by Shaggy Hiker View Post
    I would suggest going to the DateTime simply for convenience. Doing that addition is certainly possible without using TimeSpans, but TimeSpans are going to be quite a bit simpler. However, it might matter quite a bit what you will do with it in the end. After all, you are talking only about minutes and seconds, in which case you might be only interested in a sum, in which case the TimeSpan will actually work against you.

    If all you really want is the sum, then I would suggest turning the time into an integer count of seconds. For example, if the strings are "MM:SS", you might Split on ":", take the resulting array(0) * 60 + array(1) (converting both array(0) and array(1) to integers first, of course). Then you would just be summing total seconds. From that, if you want minutes, then integer divide by 60.

    That would assume that you don't care about the minutes and seconds as time, but just as a count. A TimeSpan will want those minutes and seconds to be time, and time has hours.

    Yes I just want the sum in minutes and seconds. I do not want hours part of the equation. The idea was to bring in 26 values that are currently written as and to be read as mm:ss. I was going to store these values in arrtime(25), add the values and display a total sum. So for example the values I currently have add up to 210 minutes and 17 seconds. I want to display 210:17. It was my understanding in using DateTime, you cannot go above 60. Once you reach 59, the next number is 00 and then you start adding hours. So I believed I needed to use the TimeSpan to get around that problem.

    These values are stored in a text file. I am tracking different amounts of time for 26 weeks, so there are 26 entries. Then those values will be erased and I'll collect a new set of values over another 26 weeks.

    I think I have an idea how to do this now. I'll report back a solution.

  8. #8
    Smooth Moperator techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,383

    Re: Adding Time mm:ss

    TimeSpan is the way to do... and it's not that you can't go over 60 with a DateTime, it's that hte hour then clicks over (or the Date portion will if it passes midnight) ... but then you'd have to back into the minues again by finding out the hours and tiems 60 blah blah blah.... Just use a TimeSpan and .TotalMinutes and .Seconds, plus a String.Format and you should be fine.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  9. #9
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,616

    Re: Adding Time mm:ss

    Yeah. The more I think about it, the more it just comes down to parsing the string into something useful. I'm not sure which will be the shortest, but it won't really matter much. They'll be about the same either way.
    My usual boring signature: Nothing

  10. #10
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,684

    Re: Adding Time mm:ss

    Based on post #3,

    Code:
            Dim totMins As Integer = (((accum.Days * 24) + accum.Hours) * 60) + accum.Minutes
            Dim totStr As String = String.Format("{0}:{1}", totMins, accum.Seconds.ToString.PadLeft(2, "0"c))
    Post #3 assumes that the values arrtime are less than 60 minutes, so nothing like 60:52.
    Last edited by dbasnett; Sep 26th, 2023 at 08:46 AM.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  11. #11
    Smooth Moperator techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,383

    Re: Adding Time mm:ss

    no... that's not the way... go back and read post #6 ...you CAN have minutes that exceed 60... And you get to it through the .TotalMinutes method... there's no need to go through all that calculation when it already gives it to you.


    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  12. #12
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,684

    Re: Adding Time mm:ss

    Quote Originally Posted by techgnome View Post
    no... that's not the way... go back and read post #6 ...you CAN have minutes that exceed 60... And you get to it through the .TotalMinutes method... there's no need to go through all that calculation when it already gives it to you.


    -tg
    Here are some values.

    Code:
    10:01
    10:02
    40:34
    50:00
    50:00
    50:00
    50:00
    59:00
    .TotalMinutes = 319.61666666666667

    Using those values this is my answer, 319:37.

    Yes I see you could use Math.Floor. Probably clearer IF you know what it does
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  13. #13
    Smooth Moperator techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,383

    Re: Adding Time mm:ss

    Quote Originally Posted by the_docs
    Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.
    Source: https://learn.microsoft.com/en-us/do...s?view=net-7.0

    DOH! I didn't realize it returned fraction... yeah you'd have to truncate it some how... that's kinda lame.

    There should be a flag on that to indicate of partials should be returned... I don't remember that being an issue when I worked with it... but maybe it was,... ugh... I hereby retract my endorsement of the TotalMinutes property.


    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  14. #14
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    3,012

    Re: Adding Time mm:ss

    Totalminutes will work with the correct format ..00:00:00

    Code:
    Public Class Form7
    
        Dim tb As New DataTable
    
    
        Private Sub Form7_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            tb.Columns.Add("ID")
            tb.Columns.Add("TimeInMin")
            tb.Rows.Add("1", "00:10:01")
            tb.Rows.Add("2", "00:10:02")
            tb.Rows.Add("3", "00:40:34")
            tb.Rows.Add("4", "00:50:00")
            tb.Rows.Add("5", "00:50:00")
            tb.Rows.Add("4", "00:50:00")
            tb.Rows.Add("5", "00:59:00")
            DataGridView1.DataSource = tb
        End Sub
    
        Public Function SumUpTime(ByVal TB As DataTable, _
                               ByVal col As String) As TimeSpan
            Dim s As TimeSpan = TimeSpan.Zero
            For Each Rw As DataRow In TB.Rows
                s += TimeSpan.Parse(Rw(col))
            Next
            Return s
        End Function
    
        Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            Dim sTime1 As String = String.Format("{0:00}:{1:00}", _
             Math.Floor(SumUpTime(tb, "TimeInMin").TotalMinutes), SumUpTime(tb, "TimeInMin").Seconds)
            TextBox1.Text = sTime1
        End Sub
    
    
      
    End Class
    Name:  TimesCount.jpg
Views: 174
Size:  26.9 KB
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  15. #15
    Frenzied Member
    Join Date
    May 2014
    Location
    Central Europe
    Posts
    1,367

    Re: Adding Time mm:ss

    Code:
    Public Class Form1
        Dim tb As New DataTable
    
    
        Private Sub Form7_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            tb.Columns.Add("ID")
            tb.Columns.Add("TimeInMin")
            tb.Rows.Add("1", "00:10:01")
            tb.Rows.Add("2", "00:10:02")
            tb.Rows.Add("3", "00:40:34")
            tb.Rows.Add("4", "00:50:00")
            tb.Rows.Add("5", "00:50:00")
            tb.Rows.Add("4", "00:50:00")
            tb.Rows.Add("5", "00:59:00")
            DataGridView1.DataSource = tb
        End Sub
    
        Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            Dim ts As New TimeSpan(tb.Rows.OfType(Of DataRow).Select(Function(row) TimeSpan.Parse(row("TimeInMin")).Ticks).Sum)
            TextBox1.Text = $"{Math.Floor(ts.TotalMinutes)}:{ts:ss}"
        End Sub
    
    End Class
    ?

  16. #16
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,684

    Re: Adding Time mm:ss

    Not understanding how a DataTable helps. Have you seen post #4 this thread?
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  17. #17
    Frenzied Member
    Join Date
    May 2014
    Location
    Central Europe
    Posts
    1,367

    Re: Adding Time mm:ss

    Quote Originally Posted by dbasnett View Post
    Not understanding how a DataTable helps. Have you seen post #4 this thread?
    I would assume the table was just an example? ChrisE, what's the table doing here?
    If you prefer, feel free to create a text file with example values instead to be compliant with #4.

  18. #18
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,616

    Re: Adding Time mm:ss

    I would think that the datatable is solely there for the example, as it would make it easier to add the data to the grid shown in the example. I'd say ChrisE just went beyond the requirements for the sake of example.

    I'd say we have to hear from the OP, though. We've probably run past the goal line by a few extra field lengths.
    My usual boring signature: Nothing

  19. #19
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    3,012

    Re: Adding Time mm:ss

    I used a Datatable as a sample, it would be nice if the OP could post a sample of the Textfile or CSV ?
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  20. #20
    Addicted Member
    Join Date
    Jan 2022
    Posts
    211

    Re: Adding Time mm:ss

    How I would achieve this is breaking it down into total seconds then format the string from total seconds
    Code:
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim MinSecAr(24) As String
        MinSecAr(0) = "01:23"
        MinSecAr(1) = "12:34"
        MinSecAr(2) = "05:11"
        MinSecAr(3) = "15:20"
        MinSecAr(4) = "20:00"
        MinSecAr(5) = "07:30"
        MinSecAr(6) = "03:15"
        MinSecAr(7) = "25:55"
        MinSecAr(8) = "22:10"
        MinSecAr(9) = "14:09"
        MinSecAr(10) = "00:59"
        MinSecAr(11) = "09:45"
        MinSecAr(12) = "11:37"
        MinSecAr(13) = "08:08"
        MinSecAr(14) = "19:29"
        MinSecAr(15) = "33:11"
        MinSecAr(16) = "17:42"
        MinSecAr(17) = "24:56"
        MinSecAr(18) = "39:01"
        MinSecAr(19) = "50:20"
        MinSecAr(20) = "41:15"
        MinSecAr(21) = "16:32"
        MinSecAr(22) = "29:50"
        MinSecAr(23) = "32:17"
        MinSecAr(24) = "46:12"
    
        Dim TotalSec As Int32 = 0
    
        For i As Integer = 0 To MinSecAr.Length - 1
            TotalSec += Integer.Parse(MinSecAr(i).Substring(0, MinSecAr(i).IndexOf(":"c))) * 60
            TotalSec += Integer.Parse(MinSecAr(i).Substring(MinSecAr(i).IndexOf(":"c) + 1))
        Next
    
        Dim TotMin As Integer = TotalSec \ 60
        Dim RemainSec As Integer = TotalSec Mod 60
        Dim FormattedTmie As String = String.Format("{0:D2}:{1:D2}", TotMin, RemainSec)
    End Sub

  21. #21
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,684

    Re: Adding Time mm:ss

    This is where I ended up,

    Code:
            ' arrtime = IO.File.ReadAllLines("path") 'https://www.vbforums.com/showthread.php?901164-Adding-Time-mm-ss&p=5618446&viewfull=1#post5618446
            Dim accum As TimeSpan = TimeSpan.FromTicks(0)
            For Each tmval As String In arrtime
                accum = accum.Add(TimeSpan.ParseExact(tmval, "m\:ss", Globalization.CultureInfo.CurrentCulture))
            Next
            Dim totMins As Integer = Math.Floor(accum.TotalMinutes)
            Dim totStr As String = String.Format("{0}:{1}", totMins, accum.Seconds.ToString.PadLeft(2, "0"c))
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  22. #22
    Addicted Member
    Join Date
    Jan 2022
    Posts
    211

    Re: Adding Time mm:ss

    You must spread some Reputation around before giving it to dbasnett again.
    ... this is BS!

  23. #23
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,684

    Re: Adding Time mm:ss

    Quote Originally Posted by vbdotnut View Post
    ... this is BS!
    Always been like that. Thanks just the same.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  24. #24
    Addicted Member
    Join Date
    Jan 2022
    Posts
    211

    Re: Adding Time mm:ss

    Always been like that. Thanks just the same.
    No worries,
    I dont know why, but I do prefer the way I put it. Seems to be closer to satisfying the requirement and less overkill.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width