Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

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

Substring & IndexOf in a mulitline file

My program loads a text file that has the following:

19:03 - 19:05 (2 minutes)
19:05 - 19:10 (5 minutes)
19:10 - 19:10 (No Time)

When I open this file, I want the program to run through each individual line and find the minutes and hours, and if no time is recordered get '0'. I also want to have it be dynamic, so if the time is 12 minutes, it will grab '12' and not '1'.  This is what I have so far:

Private Sub oldtime()
        Dim x As Integer
        Dim s As String
        x = TextBox1.Text.IndexOf("(")

        s = TextBox1.Text.Substring(x + 1, 1)
        Console.WriteLine(x)
        Console.WriteLine(s)
End Sub

How can I get the substring command to work per line?  Or is there a different (easier?) way to make this work?
0
Ander5
Asked:
Ander5
  • 18
  • 16
1 Solution
 
S-TwilleyCommented:
What do you want done each time the time difference is found?
0
 
Ander5Author Commented:
The program is a Call Log sort of thing, so i want it to cumulitively add the times to give a total.  It does this if you don't exit the program, I just want it to add the times you save to the cumulitively sum.
0
 
S-TwilleyCommented:
Well I can rework this sample.. but this sub takes a large string i.e. the entire file... and parses it for any string matching the pattern  XX:XX - XX:XX (timediff) ... and any matches it finds, it then takes the time diff and parses that... worked on a small set of test data.

Add an import to the top of the code

Imports System.Text.RegularExpressions

Then somewhere else

    Sub GetTimeDiffs(ByVal LargeString As String)
        Dim thisRegex As New Regex("[\d]{1,2}:[\d]{1,2} - [\d]{1,2}:[\d]{1,2} \((?<1>[^\)]*)\)")
        Dim regMinutes As New Regex("(?<1>[\d]+)[\s]*minutes")
        Dim regHours As New Regex("(?<1>[\d]+)[\s]*hours")

        Dim thisMatch, minMatch, hourMatch As Match

        Dim pMatches As MatchCollection = thisRegex.Matches(LargeString)

        Dim TimeDiff As String
        Dim TotHours, TotMinutes As Integer

        For Each thisMatch In pMatches
            TimeDiff = thisMatch.Groups(1).Value
            If TimeDiff.ToLower = "no time" Then

            Else
                minMatch = regMinutes.Match(TimeDiff)
                If minMatch.Success Then
                    TotMinutes += Val(minMatch.Groups(1).Value)
                End If

                hourMatch = regHours.Match(TimeDiff)
                If hourMatch.Success Then
                    TotHours += Val(hourMatch.Groups(1).Value)
                End If

            End If
        Next

        TotHours += (Math.Floor(TotMinutes / 60))
        TotMinutes = TotMinutes Mod 60

        ' Now i dont know what you want done with the total hours and minutes... let me know if you need help modifying this

    End Sub

===================

So for instance... say a textbox help that test data you had.. and you pass  TextBox1.Text to this sub

GetTimeDiffs(TextBox1.Text)

.... at the end of the sub TotHours would be equal to 0 and TotMinutes would equal 7
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
S-TwilleyCommented:
If you like, I can give an explanation of how that regular expression actually works.. or at least the pattern of it
0
 
S-TwilleyCommented:
Actually... replace the main Regex with this
Dim thisRegex As New Regex("[\d]{1,2}:[\d]{2} - [\d]{1,2}:[\d]{2} \((?<1>[^\)]*)\)")


Ok... I'll explain it anyway :P

Dim thisRegex As New Regex("[\d]{1,2}:[\d]{1,2} - [\d]{1,2}:[\d]{1,2} \((?<1>[^\)]*)\)")

[\d]{1,2}:[\d]{2}  = \d means a digit
                                 {1,2}  means find either one or two digits in sequence
                                 : means match a colon

                                  so altogether.. match a string which has either 1 or 2 digits, followed by a colon, then followed by 2 digits

 \((?<1>[^\)]*)\)")   =  because ( and ) are special characters, we use \ to escape it
                                  \(    means match a (
                                  ?<1> means we want to keep/remember the following text enclosed in the set
                                  [^\) ]  means capture any number of characters up until you reach  )
                                  \)  means match a )

                                  so in summary... capture all characters enclosed in (  )


so if you put those two bits together.... it matches a string with two "times" followed by text enclosed in (   )
0
 
Ander5Author Commented:
if I have both hours and minutes, how would thta go (i am not familiar with Regex's)
0
 
Ander5Author Commented:
the string would look similar to:
(3 hours 56 minutes), or (10 hours 2 minutes)
0
 
S-TwilleyCommented:
the above code handles that :P

Want me to explain the rest of it?

or would you prefer some code that doesn't use Regex?
0
 
Ander5Author Commented:
it does?  from my understanding it will only recognize (xx Minutes) or (xx Hours)
0
 
S-TwilleyCommented:
TimeDiff  holds the text between  (  and  )

============
       Dim regMinutes As New Regex("(?<1>[\d]+)[\s]*minutes")
        Dim regHours As New Regex("(?<1>[\d]+)[\s]*hours")


These two are used for two seperate tests matching any digits before the words "minutes" or "hours"
=============
0
 
Ander5Author Commented:
aight, well i changed one of the strings to be '18:03 - 19:05 (1 hour 2 minutes)'
and it did not get the hour (did the minutes, '9', fine though)
0
 
S-TwilleyCommented:
ahhh sorry.. a slight change then :P


       Dim regMinutes As New Regex("(?<1>[\d]+)[\s]*minute")
        Dim regHours As New Regex("(?<1>[\d]+)[\s]*hour")

0
 
Ander5Author Commented:
ok that works, now im trying to add new times to it (using hte prog) and having it update.
0
 
S-TwilleyCommented:
Are you ok with this method of pulling out the values?   If it's too much to grasp all in one go, just say so :)   ... but I'm happy to explain more about the Regular expressions involved in this sample if you like
0
 
Ander5Author Commented:
nah, this is good i need to learn new things :D
0
 
Ander5Author Commented:
hmm this is interesting, when i step through the program after punching in and out (adding 1 minute) the prog returns 3 hours and 27 minutes..should i send you the program?
0
 
S-TwilleyCommented:
sure
0
 
Ander5Author Commented:
do you want it emailed or posted?
0
 
Ander5Author Commented:
it is almost 400 lines, if that is a deciding factor
0
 
S-TwilleyCommented:
If you hold on a sec... just going to give you a modified sub, which might make things neater for you...

Now you can pass two integers to the sub to hold the total hours... then you can make subsequent calls to the sub with more Time strings and pass those integers again to keep a running total.

=====================

    Sub GetTimeDiffs(ByVal LargeString As String, ByRef TotHours As Integer, ByRef TotMinutes As Integer)
        Dim thisRegex As New Regex("[\d]{1,2}:[\d]{2} - [\d]{1,2}:[\d]{2} \((?<1>[^\)]*)\)")
        Dim regMinutes As New Regex("(?<1>[\d]+)[\s]*minute")
        Dim regHours As New Regex("(?<1>[\d]+)[\s]*hour")

        Dim thisMatch, minMatch, hourMatch As Match

        Dim pMatches As MatchCollection = thisRegex.Matches(LargeString)

        Dim TimeDiff As String

        For Each thisMatch In pMatches
            TimeDiff = thisMatch.Groups(1).Value
            If TimeDiff.ToLower = "no time" Then

            Else
                minMatch = regMinutes.Match(TimeDiff)
                If minMatch.Success Then
                    TotMinutes += Val(minMatch.Groups(1).Value)
                End If

                hourMatch = regHours.Match(TimeDiff)
                If hourMatch.Success Then
                    TotHours += Val(hourMatch.Groups(1).Value)
                End If

            End If
        Next

        TotHours += (Math.Floor(TotMinutes / 60))
        TotMinutes = TotMinutes Mod 60

    End Sub


================

So you program might have

Dim RunningHoursTotal, RunningMinutesTotal As Integer

Sub something()
        ....
         GetTimeDiffs(TextFromFile, RunningHoursTotal, RunningMinutesTotal)
         ....
End Sub

Sub someother()
        ....
         GetTimeDiffs(NewAddedTextFromProg, RunningHoursTotal, RunningMinutesTotal)
         ....
End Sub

===============

Not sure if that will clear anything up for you... if not, just post it here  (maybe exclude the form  generated code)
0
 
Ander5Author Commented:
still does a similar thing, here is the program
0
 
Ander5Author Commented:
Imports System.IO
Imports System.Text.RegularExpressions
Public Class Form1
    Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents MainMenu1 As System.Windows.Forms.MainMenu
    Friend WithEvents tsoptions As System.Windows.Forms.MenuItem
    Friend WithEvents savets As System.Windows.Forms.MenuItem
    Friend WithEvents loadts As System.Windows.Forms.MenuItem
    Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
    Friend WithEvents ofd As System.Windows.Forms.OpenFileDialog
    Friend WithEvents sfd As System.Windows.Forms.SaveFileDialog
    Friend WithEvents ttltime As System.Windows.Forms.MenuItem
    Friend WithEvents exitprog As System.Windows.Forms.MenuItem
    Friend WithEvents ttlboxlbl As System.Windows.Forms.Label
    Friend WithEvents ttlbox As System.Windows.Forms.Label
    Friend WithEvents NotifyIcon1 As System.Windows.Forms.NotifyIcon
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container
        Me.Button1 = New System.Windows.Forms.Button
        Me.MainMenu1 = New System.Windows.Forms.MainMenu
        Me.tsoptions = New System.Windows.Forms.MenuItem
        Me.savets = New System.Windows.Forms.MenuItem
        Me.loadts = New System.Windows.Forms.MenuItem
        Me.ttltime = New System.Windows.Forms.MenuItem
        Me.exitprog = New System.Windows.Forms.MenuItem
        Me.TextBox1 = New System.Windows.Forms.TextBox
        Me.ofd = New System.Windows.Forms.OpenFileDialog
        Me.sfd = New System.Windows.Forms.SaveFileDialog
        Me.ttlboxlbl = New System.Windows.Forms.Label
        Me.ttlbox = New System.Windows.Forms.Label
        Me.NotifyIcon1 = New System.Windows.Forms.NotifyIcon(Me.components)
        Me.SuspendLayout()
        '
        'Button1
        '
        Me.Button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat
        Me.Button1.Location = New System.Drawing.Point(9, 210)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(228, 23)
        Me.Button1.TabIndex = 2
        Me.Button1.Text = "Punch In"
        '
        'MainMenu1
        '
        Me.MainMenu1.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.tsoptions})
        '
        'tsoptions
        '
        Me.tsoptions.Index = 0
        Me.tsoptions.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.savets, Me.loadts, Me.ttltime, Me.exitprog})
        Me.tsoptions.Shortcut = System.Windows.Forms.Shortcut.CtrlShiftF
        Me.tsoptions.Text = "File"
        '
        'savets
        '
        Me.savets.DefaultItem = True
        Me.savets.Index = 0
        Me.savets.Shortcut = System.Windows.Forms.Shortcut.CtrlS
        Me.savets.Text = "Save"
        '
        'loadts
        '
        Me.loadts.Index = 1
        Me.loadts.Shortcut = System.Windows.Forms.Shortcut.CtrlO
        Me.loadts.Text = "Open"
        '
        'ttltime
        '
        Me.ttltime.Index = 2
        Me.ttltime.Shortcut = System.Windows.Forms.Shortcut.CtrlT
        Me.ttltime.Text = "Total Time"
        '
        'exitprog
        '
        Me.exitprog.Index = 3
        Me.exitprog.Shortcut = System.Windows.Forms.Shortcut.CtrlE
        Me.exitprog.Text = "Exit"
        '
        'TextBox1
        '
        Me.TextBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
        Me.TextBox1.Enabled = False
        Me.TextBox1.Location = New System.Drawing.Point(8, 8)
        Me.TextBox1.Multiline = True
        Me.TextBox1.Name = "TextBox1"
        Me.TextBox1.Size = New System.Drawing.Size(228, 200)
        Me.TextBox1.TabIndex = 4
        Me.TextBox1.Text = ""
        '
        'ttlboxlbl
        '
        Me.ttlboxlbl.Location = New System.Drawing.Point(8, 240)
        Me.ttlboxlbl.Name = "ttlboxlbl"
        Me.ttlboxlbl.Size = New System.Drawing.Size(112, 18)
        Me.ttlboxlbl.TabIndex = 5
        Me.ttlboxlbl.Text = "Total: "
        Me.ttlboxlbl.TextAlign = System.Drawing.ContentAlignment.MiddleRight
        Me.ttlboxlbl.Visible = False
        '
        'ttlbox
        '
        Me.ttlbox.Location = New System.Drawing.Point(122, 240)
        Me.ttlbox.Name = "ttlbox"
        Me.ttlbox.Size = New System.Drawing.Size(112, 18)
        Me.ttlbox.TabIndex = 6
        Me.ttlbox.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        Me.ttlbox.Visible = False
        '
        'NotifyIcon1
        '
        Me.NotifyIcon1.Text = "NotifyIcon1"
        Me.NotifyIcon1.Visible = True
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(248, 265)
        Me.Controls.Add(Me.ttlbox)
        Me.Controls.Add(Me.ttlboxlbl)
        Me.Controls.Add(Me.TextBox1)
        Me.Controls.Add(Me.Button1)
        Me.Menu = Me.MainMenu1
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)

    End Sub

#End Region
    Dim iHrs, iMin, oHrs, oMin, wHrs, wMin, tHrs, tMin As Integer
    Dim punched As Boolean = False
    Dim pIn As Boolean = False
    Dim col As String
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        TextBox1.Text = Nothing
    End Sub
    Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        buttonswitch()
    End Sub
    Private Sub buttonswitch()
        If pIn = False Then
            Button1.Text = "Punch Out"
            Dim iTime As String = Format(Now(), "HH:mm")
            punchI(iTime)
            pIn = True
        Else
            Button1.Text = "Punch In"
            Dim oTime As String = Format(Now(), "HH:mm")
            punchO(oTime)

            pIn = False
        End If
    End Sub
    Private Sub punchI(ByVal iTime As String)
        TextBox1.Text &= iTime
        iHrs = iTime.Substring(0, 2)
        iMin = iTime.Substring(3, 2)
    End Sub
    Sub GetTimeDiffs(ByVal LargeString As String, ByRef tHrs As Integer, ByRef tMin As Integer)
        Dim thisRegex As New Regex("[\d]{1,2}:[\d]{2} - [\d]{1,2}:[\d]{2} \((?<1>[^\)]*)\)")
        Dim regMinutes As New Regex("(?<1>[\d]+)[\s]*minute")
        Dim regHours As New Regex("(?<1>[\d]+)[\s]*hour")

        Dim thisMatch, minMatch, hourMatch As Match

        Dim pMatches As MatchCollection = thisRegex.Matches(LargeString)

        Dim TimeDiff As String

        For Each thisMatch In pMatches
            TimeDiff = thisMatch.Groups(1).Value
            If TimeDiff.ToLower = "no time" Then

            Else
                minMatch = regMinutes.Match(TimeDiff)
                If minMatch.Success Then
                    tMin += Val(minMatch.Groups(1).Value)
                End If

                hourMatch = regHours.Match(TimeDiff)
                If hourMatch.Success Then
                    tHrs += Val(hourMatch.Groups(1).Value)
                End If

            End If
        Next

        tHrs += (Math.Floor(tMin / 60))
        tMin = tMin Mod 60

    End Sub

    Private Sub oldtime(ByVal LargeString As String)
        'Dim x As Integer
        'Dim s As String
        'x = TextBox1.Text.IndexOf("(")
        's = TextBox1.Text.Substring(x + 1, 1)
        'Console.WriteLine(x)
        'Console.WriteLine(s)
        Dim thisRegex As New Regex("[\d]{1,2}:[\d]{2} - [\d]{1,2}:[\d]{2} \((?<1>[^\)]*)\)")
        Dim regMinutes As New Regex("(?<1>[\d]+)[\s]*minute")
        Dim regHours As New Regex("(?<1>[\d]+)[\s]*hour")
        Dim regBoth

        Dim thisMatch, minMatch, hourMatch As Match

        Dim pMatches As MatchCollection = thisRegex.Matches(LargeString)

        Dim TimeDiff As String
        'Dim tHrs, tMin As Integer

        For Each thisMatch In pMatches
            TimeDiff = thisMatch.Groups(1).Value
            If TimeDiff.ToLower = "No Time" Then

            Else
                minMatch = regMinutes.Match(TimeDiff)
                If minMatch.Success Then
                    tMin += Val(minMatch.Groups(1).Value)
                End If

                hourMatch = regHours.Match(TimeDiff)
                If hourMatch.Success Then
                    tHrs += Val(hourMatch.Groups(1).Value)
                End If

            End If
        Next

        'tHrs += (Math.Floor(tMin / 60))
        'tMin += tMin Mod 60

        ' Now i dont know what you want done with the total hours and minutes... let me know if you need help modifying this

    End Sub
    Private Sub punchO(ByVal oTime As String)
        oldtime(TextBox1.Text)
        TextBox1.Text &= " - " & oTime
        oHrs = oTime.Substring(0, 2)
        oMin = oTime.Substring(3, 2)
        wHrs = oHrs - iHrs
        wMin = oMin - iMin
        If wMin = 60 Then
            wMin -= 60
            wHrs += 1
        End If
        'oldtime(textbox1.Text)
        GetTimeDiffs(TextBox1.Text, wHrs, wMin)
        If wHrs = 0 Then
            If wMin > 1 And Not wMin = 0 Then
                TextBox1.Text &= " (" & wMin & " minutes)" & vbCrLf
            ElseIf wMin = 1 Then
                TextBox1.Text &= " (" & wMin & " minute)" & vbCrLf
            ElseIf wMin = 0 And wHrs = 0 Then
                TextBox1.Text &= " (No Time)" & vbCrLf
            End If
        ElseIf wMin = 0 Then
            If wHrs > 1 And Not wHrs = 0 Then
                TextBox1.Text &= " (" & wHrs & " hours)" & vbCrLf
            ElseIf wHrs = 1 Then
                TextBox1.Text &= " (" & wMin & " hour)" & vbCrLf
            ElseIf wHrs = 0 And wMin = 0 Then
                TextBox1.Text &= " (No Time)" & vbCrLf
            End If
        ElseIf wHrs < 10 And Not wHrs = 0 And wMin < 10 And Not wMin = 0 Then
            If wHrs = 1 And Not wMin = 1 Then
                TextBox1.Text &= " (" & wHrs & " hour " & wMin & " minutes)" & vbCrLf
            ElseIf wHrs = 1 And wMin = 1 Then
                TextBox1.Text &= " (" & wHrs & " hour " & wMin & " minute)" & vbCrLf
            ElseIf Not wHrs = 1 And wMin = 1 Then
                TextBox1.Text &= " (" & wHrs & " hours " & wMin & " minute)" & vbCrLf
            End If
        ElseIf wHrs < 10 And (wMin < 10 And wMin > 0) Then
            If wHrs = 1 And Not wMin = 1 Then
                TextBox1.Text &= " (" & wHrs & " hour " & wMin & " minutes)" & vbCrLf
            ElseIf wHrs = 1 And wMin = 1 Then
                TextBox1.Text &= " (" & wHrs & " hour " & wMin & " minute)" & vbCrLf
            ElseIf Not wHrs = 1 And wMin = 1 Then
                TextBox1.Text &= " (" & wHrs & " hours " & wMin & " minute)" & vbCrLf
            End If
        ElseIf wHrs > 10 And wMin < 10 Then
            If wHrs = 1 And Not wMin = 1 Then
                TextBox1.Text &= " (" & wHrs & " hour " & wMin & " minutes)" & vbCrLf
            ElseIf wHrs = 1 And wMin = 1 Then
                TextBox1.Text &= " (" & wHrs & " hour " & wMin & " minute)" & vbCrLf
            ElseIf Not wHrs = 1 And wMin = 1 Then
                TextBox1.Text &= " (" & wHrs & " hours " & wMin & " minute)" & vbCrLf
            End If
        ElseIf wHrs < 10 And wMin > 10 Then
            If wHrs = 1 And Not wMin = 1 Then
                TextBox1.Text &= " (" & wHrs & " hour " & wMin & " minutes)" & vbCrLf
            ElseIf wHrs = 1 And wMin = 1 Then
                TextBox1.Text &= " (" & wHrs & " hour " & wMin & " minute)" & vbCrLf
            ElseIf Not wHrs = 1 And wMin = 1 Then
                TextBox1.Text &= " (" & wHrs & " hours " & wMin & " minute)" & vbCrLf
            End If
        End If
    End Sub
    Private Sub savets_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles savets.Click
        SaveTC()
    End Sub
    Private Sub loadts_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles loadts.Click
        LoadTC()
    End Sub
    Private Sub ttltime_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ttltime.Click
        calctime()
    End Sub
    Private Sub exitprog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exitprog.Click
        pInCheck()
        exitTC()
    End Sub
    Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        exitTC()
    End Sub
    Private Sub pInCheck()
        If pIn = True Then
            Dim oTime As String = Format(Now(), "HH:mm")
            punchO(oTime)
            pIn = False
            Button1.Text = "Punch in"
            exitTC()
        End If
    End Sub
    Private Sub exitTC()
        If Not TextBox1.Text = Nothing Then
            If MsgBox("Save before exit?", MsgBoxStyle.YesNo, "Save log?") = MsgBoxResult.Yes Then
                SaveTC()
            End If
        End If
        End
    End Sub
    Private Sub SaveTC()
        Dim x As Integer
        If Not TextBox1.Text = Nothing Then
            sfd.Filter = "Time Clock (*.clk)|*.clk"
            sfd.ShowDialog()
            If sfd.FileName = Nothing Then
            Else
                Dim sFile As New StreamWriter(sfd.FileName, False)
                For x = 0 To TextBox1.Text.Length - 1
                    sFile.Write(TextBox1.Text.Substring(x, 1))
                Next
                sFile.Close()
            End If
        Else
            MsgBox("There is nothing to save!", MsgBoxStyle.Exclamation)
        End If
    End Sub
    Sub LoadTC()
        TextBox1.Text = Nothing
        ofd.FileName = Nothing
        ofd.Filter = "Time Clock (*.clk)|*.clk"
        ofd.ShowDialog()
        If ofd.FileName = Nothing Then
        Else
            Dim lfile As New StreamReader(ofd.FileName)
            TextBox1.Clear()
            TextBox1.Text = lfile.ReadToEnd
            lfile.Close()
        End If
        TextBox1.Text &= vbCrLf
        'oldtime(TextBox1.Text)
        GetTimeDiffs(TextBox1.Text, tHrs, tMin)

    End Sub
    Private Sub calctime()
        ttlboxlbl.Visible = True
        If tHrs = 0 Then
            If tMin = 1 Then
                ttlbox.Text = tMin & " minute"
            ElseIf Not tMin = 1 Then
                ttlbox.Text = tMin & " minutes"
            End If
        ElseIf tMin = 0 Then
            If tHrs = 1 Then
                ttlbox.Text = tHrs & " hour"
            ElseIf Not tMin = 1 Then
                ttlbox.Text = tMin & " hours"
            End If
        ElseIf Not tHrs = 1 And Not tMin = 1 Then
            ttlbox.Text = tHrs & " hours " & tMin & " minutes"
        ElseIf tHrs = 1 And tMin = 1 Then
            ttlbox.Text = tHrs & " hour " & tMin & " minute"
        ElseIf tHrs = 1 And Not tMin = 1 Then
            ttlbox.Text = tHrs & " hour " & tMin & " minutes"
        ElseIf Not tHrs = 1 And tMin = 1 Then
            ttlbox.Text = tHrs & " hours " & tMin & " minute"
        ElseIf tHrs = 0 And tMin = 0 Then
            ttlbox.Text = "No time"
        End If
        ttlbox.Visible = True
    End Sub
End Class
0
 
Ander5Author Commented:
18:03 - 19:05 (1 hour 2 minutes)
19:03 - 19:10 (7 minutes)
19:10 - 19:10 (No Time)


make a document called <name>.clk and paste that in there, so you can load it into the program
0
 
Ander5Author Commented:
did you locate the problem?
0
 
S-TwilleyCommented:
Yeah....

Im just rewriting some of the stuff in there now... bit hard to say what I fixed now... almost finished and will paste up edited class in a moment
0
 
Ander5Author Commented:
aight thank you sir
0
 
S-TwilleyCommented:
Ok, put this in a seperate project or class just in case:

Imports System.IO
Imports System.Text.RegularExpressions
Public Class Form1
    Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents MainMenu1 As System.Windows.Forms.MainMenu
    Friend WithEvents tsoptions As System.Windows.Forms.MenuItem
    Friend WithEvents savets As System.Windows.Forms.MenuItem
    Friend WithEvents loadts As System.Windows.Forms.MenuItem
    Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
    Friend WithEvents ofd As System.Windows.Forms.OpenFileDialog
    Friend WithEvents sfd As System.Windows.Forms.SaveFileDialog
    Friend WithEvents ttltime As System.Windows.Forms.MenuItem
    Friend WithEvents exitprog As System.Windows.Forms.MenuItem
    Friend WithEvents ttlboxlbl As System.Windows.Forms.Label
    Friend WithEvents ttlbox As System.Windows.Forms.Label
    Friend WithEvents NotifyIcon1 As System.Windows.Forms.NotifyIcon
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container()
        Me.Button1 = New System.Windows.Forms.Button()
        Me.MainMenu1 = New System.Windows.Forms.MainMenu()
        Me.tsoptions = New System.Windows.Forms.MenuItem()
        Me.savets = New System.Windows.Forms.MenuItem()
        Me.loadts = New System.Windows.Forms.MenuItem()
        Me.ttltime = New System.Windows.Forms.MenuItem()
        Me.exitprog = New System.Windows.Forms.MenuItem()
        Me.TextBox1 = New System.Windows.Forms.TextBox()
        Me.ofd = New System.Windows.Forms.OpenFileDialog()
        Me.sfd = New System.Windows.Forms.SaveFileDialog()
        Me.ttlboxlbl = New System.Windows.Forms.Label()
        Me.ttlbox = New System.Windows.Forms.Label()
        Me.NotifyIcon1 = New System.Windows.Forms.NotifyIcon(Me.components)
        Me.SuspendLayout()
        '
        'Button1
        '
        Me.Button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat
        Me.Button1.Location = New System.Drawing.Point(9, 210)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(228, 23)
        Me.Button1.TabIndex = 2
        Me.Button1.Text = "Punch In"
        '
        'MainMenu1
        '
        Me.MainMenu1.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.tsoptions})
        '
        'tsoptions
        '
        Me.tsoptions.Index = 0
        Me.tsoptions.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.savets, Me.loadts, Me.ttltime, Me.exitprog})
        Me.tsoptions.Shortcut = System.Windows.Forms.Shortcut.CtrlShiftF
        Me.tsoptions.Text = "File"
        '
        'savets
        '
        Me.savets.DefaultItem = True
        Me.savets.Index = 0
        Me.savets.Shortcut = System.Windows.Forms.Shortcut.CtrlS
        Me.savets.Text = "Save"
        '
        'loadts
        '
        Me.loadts.Index = 1
        Me.loadts.Shortcut = System.Windows.Forms.Shortcut.CtrlO
        Me.loadts.Text = "Open"
        '
        'ttltime
        '
        Me.ttltime.Index = 2
        Me.ttltime.Shortcut = System.Windows.Forms.Shortcut.CtrlT
        Me.ttltime.Text = "Total Time"
        '
        'exitprog
        '
        Me.exitprog.Index = 3
        Me.exitprog.Shortcut = System.Windows.Forms.Shortcut.CtrlE
        Me.exitprog.Text = "Exit"
        '
        'TextBox1
        '
        Me.TextBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
        Me.TextBox1.Enabled = False
        Me.TextBox1.Location = New System.Drawing.Point(8, 8)
        Me.TextBox1.Multiline = True
        Me.TextBox1.Name = "TextBox1"
        Me.TextBox1.Size = New System.Drawing.Size(228, 200)
        Me.TextBox1.TabIndex = 4
        Me.TextBox1.Text = ""
        '
        'ttlboxlbl
        '
        Me.ttlboxlbl.Location = New System.Drawing.Point(8, 240)
        Me.ttlboxlbl.Name = "ttlboxlbl"
        Me.ttlboxlbl.Size = New System.Drawing.Size(112, 18)
        Me.ttlboxlbl.TabIndex = 5
        Me.ttlboxlbl.Text = "Total: "
        Me.ttlboxlbl.TextAlign = System.Drawing.ContentAlignment.MiddleRight
        Me.ttlboxlbl.Visible = False
        '
        'ttlbox
        '
        Me.ttlbox.Location = New System.Drawing.Point(122, 240)
        Me.ttlbox.Name = "ttlbox"
        Me.ttlbox.Size = New System.Drawing.Size(112, 18)
        Me.ttlbox.TabIndex = 6
        Me.ttlbox.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        Me.ttlbox.Visible = False
        '
        'NotifyIcon1
        '
        Me.NotifyIcon1.Text = "NotifyIcon1"
        Me.NotifyIcon1.Visible = True
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(248, 265)
        Me.Controls.Add(Me.ttlbox)
        Me.Controls.Add(Me.ttlboxlbl)
        Me.Controls.Add(Me.TextBox1)
        Me.Controls.Add(Me.Button1)
        Me.Menu = Me.MainMenu1
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)

    End Sub

#End Region
    Dim punched As Boolean = False
    Dim pIn As Boolean = False
    Dim col As String

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        TextBox1.Text = Nothing
    End Sub
    Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        buttonswitch()
    End Sub

    Dim inTime As DateTime

    Private Sub buttonswitch()
        If pIn = False Then
            Button1.Text = "Punch Out"
            inTime = New DateTime(Now.Year, Now.Month, Now.Day, Now.Hour, Now.Minute, 0)
            punchI(inTime)

            pIn = True
        Else
            Button1.Text = "Punch In"

            Dim outTime As New DateTime(Now.Year, Now.Month, Now.Day, Now.Hour, Now.Minute, 0)
            punchO(outTime)

            pIn = False
        End If
    End Sub

    Sub GetTimeDiffs(ByVal LargeString As String, ByRef tHrs As Integer, ByRef tMin As Integer)
        Dim thisRegex As New Regex("[\d]{1,2}:[\d]{2} - [\d]{1,2}:[\d]{2} \((?<1>[^\)]*)\)")
        Dim regMinutes As New Regex("(?<1>[\d]+)[\s]*minute")
        Dim regHours As New Regex("(?<1>[\d]+)[\s]*hour")

        Dim thisMatch, minMatch, hourMatch As Match

        Dim pMatches As MatchCollection = thisRegex.Matches(LargeString)

        Dim TimeDiff As String

        For Each thisMatch In pMatches
            TimeDiff = thisMatch.Groups(1).Value
            If TimeDiff.ToLower = "no time" Then

            Else
                minMatch = regMinutes.Match(TimeDiff)
                If minMatch.Success Then
                    tMin += Val(minMatch.Groups(1).Value)
                End If

                hourMatch = regHours.Match(TimeDiff)
                If hourMatch.Success Then
                    tHrs += Val(hourMatch.Groups(1).Value)
                End If

            End If
        Next

        tHrs += (Math.Floor(tMin / 60))
        tMin = tMin Mod 60

    End Sub

    Private Sub punchI(ByVal iTime As DateTime)
        TextBox1.Text &= iTime.ToString("HH:mm")

    End Sub
    Private Sub punchO(ByVal oTime As DateTime)

        TextBox1.Text &= " - " & oTime.ToString("HH:mm")

        Dim clockedTime As TimeSpan = oTime.Subtract(inTime)
        Dim wHrs, wMin As Integer

        wHrs = clockedTime.Hours
        wMin = clockedTime.Minutes

        Dim sHours As String = ""
        Dim sMinutes As String = ""


        If wHrs = 1 Then sHours = "1 hour"
        If wHrs > 1 Then sHours = wHrs & " hours"

        If wHrs >= 1 And wMin >= 1 Then sHours &= " "

        If wMin = 1 Then sMinutes = "1 minute"
        If wMin > 1 Then sMinutes = wMin & " minutes"

        If wHrs + wMin = 0 Then
            TextBox1.Text &= " (No Time)" & vbCrLf
        Else
            TextBox1.Text &= " (" & sHours & sMinutes & ")" & vbCrLf
        End If
    End Sub
    Private Sub savets_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles savets.Click
        SaveTC()
    End Sub
    Private Sub loadts_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles loadts.Click
        LoadTC()
    End Sub
    Private Sub ttltime_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ttltime.Click
        calctime()
    End Sub
    Private Sub exitprog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exitprog.Click
        pInCheck()
        exitTC()
    End Sub
    Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        exitTC()
    End Sub
    Private Sub pInCheck()
        If pIn = True Then
            Dim oTime As String = Format(Now(), "HH:mm")
            punchO(oTime)
            pIn = False
            Button1.Text = "Punch in"
            exitTC()
        End If
    End Sub
    Private Sub exitTC()
        If Not TextBox1.Text = Nothing Then
            If MsgBox("Save before exit?", MsgBoxStyle.YesNo, "Save log?") = MsgBoxResult.Yes Then
                SaveTC()
            End If
        End If
        End
    End Sub
    Private Sub SaveTC()
        Dim x As Integer
        If Not TextBox1.Text = Nothing Then
            sfd.Filter = "Time Clock (*.clk)|*.clk"
            sfd.ShowDialog()
            If sfd.FileName = Nothing Then
            Else
                Dim sFile As New StreamWriter(sfd.FileName, False)
                For x = 0 To TextBox1.Text.Length - 1
                    sFile.Write(TextBox1.Text.Substring(x, 1))
                Next
                sFile.Close()
            End If
        Else
            MsgBox("There is nothing to save!", MsgBoxStyle.Exclamation)
        End If
    End Sub
    Sub LoadTC()
        TextBox1.Text = Nothing
        ofd.FileName = Nothing
        ofd.Filter = "Time Clock (*.clk)|*.clk"
        ofd.ShowDialog()
        If ofd.FileName = Nothing Then
        Else
            Dim lfile As New StreamReader(ofd.FileName)
            TextBox1.Clear()
            TextBox1.Text = lfile.ReadToEnd
            lfile.Close()
        End If
        TextBox1.Text &= vbCrLf

    End Sub
    Private Sub calctime()
        ttlboxlbl.Visible = True
        ttlbox.Text = ""

        Dim newHours, newMinutes As Integer
        GetTimeDiffs(TextBox1.Text, newHours, newMinutes)


        Dim sHours As String = ""
        Dim sMinutes As String = ""

        If newHours = 1 Then sHours = "1 hour"
        If newHours > 1 Then sHours = newHours & " hours"

        If newHours >= 1 And newMinutes >= 1 Then sHours &= " "

        If newMinutes = 1 Then sMinutes = "1 minute"
        If newMinutes > 1 Then sMinutes = newMinutes & " minutes"

        If newHours + newMinutes = 0 Then
            ttlbox.Text &= "(No Time)" & vbCrLf
        Else
            ttlbox.Text &= "(" & sHours & sMinutes & ")" & vbCrLf
        End If

        ttlbox.Visible = True
    End Sub
End Class

=====================

I've made a few bits more efficient... think it is still doing the same... I'll carry on looking through it to see if there are any other parts to improve
0
 
S-TwilleyCommented:
just noticed this part...  replace the sub with the one below

    Private Sub pInCheck()
        If pIn = True Then
            buttonswitch             '  This emulates clicking the clock in button again... figure its better that way?

            exitTC()
        End If
    End Sub
0
 
Ander5Author Commented:
ok it works properly now, what was the deal beforehand why it was adding hours and minutes?
0
 
S-TwilleyCommented:
if i remember right... it's because you were continually using the whole of the textbox... and "reparsing" over the values you had already done...

when you loaded data in you called...

      GetTimeDiffs(TextBox1.Text, tHrs, tMin)


... and when clocked out...

GetTimeDiffs(TextBox1.Text, wHrs, wMin)


which is going over the same data again

I think that's where the problem was.
0
 
Ander5Author Commented:
ahh ok, well thank you very much...do you have email so that if i have other questions i can contact you?
0
 
S-TwilleyCommented:
Posting problems on here is fine... Im usually about.. and check a few times each hour except when im sleeping.
0
 
Ander5Author Commented:
Ok, thanks again
0
 
S-TwilleyCommented:
Glad to be of help...

As for regular expressions, the VB.NET help file should have a few examples on how to use them.  Think the examples how you how to extract data from a url,  from HTML code and something else, I forget... so have a look at those, and should help you to get started.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

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