Convert minutes to hours: ,minutes in vb.net - vb.net

I want to convert total minutes to hours and minutes hh:mm..
This is my code
Private Sub TextBox5_TextChanged(sender As Object, e As EventArgs) Handles TextBox5.TextChanged
Dim TotalMinute As Int32
Dim Minute As Int32
Dim Hour As Int32
Try
TotalMinute = CType(TextBox9.Text, Int32)
TotalMinute = TotalMinute Mod 1440
Hour = TotalMinute \ 60
Minute = TotalMinute Mod 60
TextBox5.Text = FormatTwoDigits(Hour) & ":" & FormatTwoDigits(Minute)
Catch ex As Exception
Exit Sub
End Try
End Sub
Private Function FormatTwoDigits(ByVal i As Int32) As String
If 30 > i Then
FormatTwoDigits = "0" & i.ToString
Else
FormatTwoDigits = i.ToString
End If
End Function
This code works fine under 24 hours.. but counts back from 0 after 24...
For example if the input is 1500 minutes it should say 25:00 not 01:00

Or you could let .Net do the work
Dim ts As TimeSpan = TimeSpan.FromMinutes(TotalMinute)
Dim s As String = String.Format("{0:00}:{1:00}", Math.Floor(ts.TotalHours), ts.Minutes)

Remove your TotalMinute = TotalMinute Mod 1440 line, which is saying to get rid of any "day" portion if the total minutes exceeds one day. (60 minutes = 1 hour, 24 hours = 1 day, therefore 1440 minutes = 1 day.)

I'd do something more like:
Private Sub TextBox5_TextChanged(sender As Object, e As EventArgs) Handles TextBox5.TextChanged
Dim TotalMinute As Integer
If Integer.TryParse(TextBox9.Text, TotalMinute) Then
Dim ts As TimeSpan = TimeSpan.FromMinutes(TotalMinute)
TextBox5.Text = CType(ts.TotalHours, Integer).ToString("00") & ":" & ts.Minutes.ToString("00")
End If
End Sub

Related

How to convert string to timespan ? visual basic, stopwatch, lap system

I am a beginer and making a stopwatch with lap feature using visual studio 2012, visual basic. Now I stuck in the lap feature. In the lap feature I want to display the result using listview ...
When the user click the lap button 2nd times it has to show the lap time between first click and 2nd click.. but i m not getting the result. Is here anybody to resolve my problem ? thank u in advance
here is the code of lap button event
Private Sub btnLap_Click(sender As Object, e As EventArgs) Handles btnLap.Click
Dim lap As String = (sw.Elapsed.Hours.ToString("00") & ":" & sw.Elapsed.Minutes.ToString("00") & _
":" & sw.Elapsed.Seconds.ToString("00") & ":" & sw.Elapsed.Milliseconds.ToString("00"))
lapcount += 1
Dim i As Integer = ListView1.Items.Count
If i <= 0 Then
ListView1.Items.Add(CStr(lapcount), i)
ListView1.Items(i).SubItems.Add(lap)
ListView1.Items(i).SubItems.Add(lap)
Else
ListView1.Items.Add(CStr(lapcount), i)
ListView1.Items(i).SubItems.Add(lap)
ListView1.Items(i).SubItems.Add((TimeSpan.parse(lap)- Timespan.parse(lastlap)).ToString) ''' I can't subtract the value from 2nd click to first click
End If
lastlap = (ListView1.Items(i).SubItems(1).ToString)
End Sub
To be honest, its usually a bad idea to use UI objects as your primary store of data. You would be much better storing the split times in a List (Of TimeSpan) and calculating calculating the lap times from that.
In my sample I declared some class objects so that the code would run. You could adapt these as necessary.
Dim sw As New Stopwatch
Dim lapcount As Integer = 1
Dim lastlap As Integer
Dim lapintervals As New List(Of TimeSpan)
Dim timeFormat As String = "hh\:mm\:ss\.fff"
So in your button click event you would have something like this ..
Private Sub BtnLap_Click(sender As Object, e As EventArgs) Handles BtnLap.Click
Dim ts As TimeSpan = sw.Elapsed
lapintervals.Add(ts)
AddTimeToListView(lapintervals.Count, lapintervals.Last)
lapcount += 1
End Sub
And you would add the info to your ListView like this
Private Sub AddTimeToListView(lapcount As Integer, lapsplit As TimeSpan)
Dim lvItem As New ListViewItem(lapcount.ToString, lapcount)
If lapcount = 1 Then
lvItem.SubItems.Add(lapsplit.ToString(timeFormat))
lvItem.SubItems.Add(lapsplit.ToString(timeFormat))
Else
lvItem.SubItems.Add(lapsplit.ToString(timeFormat))
lvItem.SubItems.Add((lapsplit.Subtract(lapintervals(lapcount - 2))).ToString(timeFormat))
End If
ListView1.Items.Add(lvItem)
End Sub
thenk you very much for answering...
finally i have finished my stopwatch application ..
i've made this and my leader gave me 8 out of 10 .. it pretty much good for me
here is the design form and code
visual basic 2012, stopwatch with lap button
enter image description here
[code]
Public Class Stopwatch
Public watch As Form 'スタートページから呼び出すため
Dim sw As New System.Diagnostics.Stopwatch()
Dim lapcount As Integer
Dim lastlap As String
'スタート・ストップボタン
Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
If btnStart.Text = "Start" Then
sw.Start() '時間計測開始
Timer1.Interval = 10
Timer1.Enabled = True
btnStart.Text = "Stop"
Else
sw.Stop() '時間計測一時停止
Timer1.Enabled = False
btnStart.Text = "Start"
End If
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
lblTime.Text = sw.Elapsed.ToString("hh\:mm\:ss\:ff")
End Sub
'cancel / reset ボタン
Private Sub btnReset_Click(sender As Object, e As EventArgs) Handles btnReset.Click
sw.Reset() '初期状態にする
Timer1.Enabled = False
lblTime.Text = "00:00:00:00"
ListView1.Items.Clear()
btnStart.Text = "Start"
lapcount = 0
End Sub
'ラップボタン
Private Sub btnLap_Click(sender As Object, e As EventArgs) Handles btnLap.Click
Dim lap = sw.Elapsed.ToString("hh\:mm\:ss\:fff") ' ラップ時間を変数に代入
lapcount += 1
Dim i As Integer = ListView1.Items.Count
If i <= 0 Then ' ListviewのアイテムのValueが0または0より小さければ
ListView1.Items.Add(CStr(lapcount), i)
ListView1.Items(i).SubItems.Add(lap) 'アイテムとサブアイテム表示
ListView1.Items(i).SubItems.Add(lap)
Else '文字列となっている結果時間を整数型に変換する/ // ラップ経過時間を取得するため
Dim day As Integer = 0
Dim hr As Integer = CInt(Strings.Left(lap, 2))
Dim min As Integer = CInt(Strings.Mid(lap, 4, 2))
Dim sec As Integer = CInt(Strings.Mid(lap, 7, 2))
Dim milli As Integer = CInt(Strings.Mid(lap, 10, 3))
Dim dayy As Integer = 0
Dim hrr As Integer = CInt(Strings.Mid(lastlap, 19, 2))
Dim minn As Integer = CInt(Strings.Mid(lastlap, 22, 2))
Dim secc As Integer = CInt(Strings.Mid(lastlap, 25, 2))
Dim millii As Integer = CInt(Strings.Mid(lastlap, 28, 3))
'現在のラップ時間に直前に記憶したラップ時間を引き、1回目から2回目のラップボタン押下までの経過時間を図る
Dim answer = createtimespan(day, hr, min, sec, milli) - createtimespan(dayy, hrr, minn, secc, millii)
Dim ansTS = answer.ToString("hh\:mm\:ss\:fff") 'ミリ秒3桁まで表示するように指定
ListView1.Items.Add(CStr(lapcount), i)
ListView1.Items(i).SubItems.Add(lap)
ListView1.Items(i).SubItems.Add((ansTS).ToString) 'ラップ時間の表示
End If
lastlap = ListView1.Items(i).SubItems(1).ToString '直前のラップタイムを記憶
End Sub
Private Function createtimespan(ByVal days As Integer, ByVal hours As Integer, ByVal minutes As Integer, _
ByVal seconds As Integer, ByVal milliseconds As Integer) As TimeSpan
Dim elapsedTime As New TimeSpan(days, hours, minutes, seconds, milliseconds)
Return (elapsedTime)
End Function
End Class

Winforms timer not accurate

I have an app that uses a System.Windows.Forms.Timer and am seeing issues with the timer interval. When I use an interval of 1000 for a duration of 180 seconds the elapsed time is consistently around 183 seconds. When I use an interval of 995, the elapsed time is accurate (i.e. 180 seconds). I have tried this on 3 different PCs with the same results on each. The code below uses 2 textboxes to display the start and end times and a label as a countdown timer.
Can anyone explain this behavior?
Public Class Form1
Private WithEvents tmr As New System.Windows.Forms.Timer
Private Duration As Integer = 180
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RunTimer()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lblActivityTimer.Text = FormatCounter(Duration)
tmr.Interval = 1000
End Sub
Private Sub RunTimer()
tmr.Start()
TextBox1.Text = Now.ToString()
End Sub
Private Function FormatCounter(sec As Integer) As String
Dim Hours, Minutes, Seconds As Integer
Hours = sec \ 3600
Seconds = sec Mod 3600
Minutes = Seconds \ 60
Seconds = sec Mod 60
FormatCounter = Hours.ToString.PadLeft(2, "0"c) & ":" _
& Minutes.ToString.PadLeft(2, "0"c) _
& ":" _
& Seconds.ToString.PadLeft(2, "0"c)
End Function
Private Sub tmr_Tick(sender As Object, e As EventArgs) Handles tmr.Tick
Duration -= 1
lblActivityTimer.Text = FormatCounter(Duration)
If Duration = 0 Then
TextBox2.Text = Now.ToString()
tmr.Stop()
End If
End Sub
End Class
Use a Stop Watch, it provides a set of methods and properties that you can use to accurately measure elapsed time.
Shared Sub Main(ByVal args() As String)
Dim stopWatch As New Stopwatch()
stopWatch.Start()
Thread.Sleep(10000)
stopWatch.Stop()
' Get the elapsed time as a TimeSpan value.
Dim ts As TimeSpan = stopWatch.Elapsed
' Format and display the TimeSpan value.
Dim elapsedTime As String = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10)
Console.WriteLine( "RunTime " + elapsedTime)
End Sub 'Main
There are two readily available Timer object alternatives:
System.Threading.Timer (explained here, my first pick)
System.Timers.Timer (explained here)

Progressbar decrement using datetime

I am trying to decrement timer from 30 minutes to 0 mins and update the progressbar with the decrement of time
I have a progressbar control on my form and set it's min val to '0' and max value to '60' and incremental step to '1'
I have stucked with it right now..
This is what I have done so far:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ProgressBar1.Value = 60
End sub
Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
Dim dFrom As DateTime
Dim dTo As DateTime
Dim sDateFrom As String = DateTime.Now
Dim sDateTo As String = lblLogOutTime.Text
If RemainingTime.Text = "00:00:00" Then
RemainingTime.Text = "Time's up!"
ProgressBar1.Value = 0
Timer2.Stop()
ElseIf DateTime.TryParse(sDateFrom, dFrom) AndAlso DateTime.TryParse(sDateTo, dTo) Then
Timer2.Start()
ProgressBar1.Value -= 1
ProgressBar1.Update()
Dim TS As TimeSpan = dTo - dFrom
Dim hour As Integer = TS.Hours
Dim mins As Integer = TS.Minutes
Dim secs As Integer = TS.Seconds
Dim timeDiff As String = ((hour.ToString("00") & ":") + mins.ToString("00") & ":") + secs.ToString("00")
RemainingTime.Text = timeDiff
End If
It seems like you have a lot of extra code in there. For instance DateTime types converted to string, then back to Date.
Private LogOutTime as Date ' destination time
Form Load/Restart sub:
LogOutTime = DateTime.Now.AddMinutes(30)
' 1 min tick
Timer2.Interval = 60 * 1000 ' 1 min timer
ProgressBar1.Value = 30 ' 30 min countdown
ProgressBar1.Maximum = 31
Timer2.Start
Private Sub Timer2_Tick(...
Dim Ts as TimeSpan = LogOutTime - DateTime.Now
If Ts.Minutes = 0 Then ' or TS,Ticks
RemainingTime.Text = "Time's up!"
ProgressBar1.Value = 0
Timer2.Stop()
Exit Sub
End If
' better to convert Ts.Ticks to a 0-30 value
' so the timer interval can be different than 1 min
ProgressBar1.Value -= 1
RemainingTime.Text = New DateTime(Ts.Ticks).ToString("hh:mm:ss")
Timer2.Start()
End Sub
There are several ways to format the time remaining depending on your .NET version. I dont know what Timer1 does, it might interfere. If the Timer interval was 20 or 30 secs you could show seconds ticking away but you'd have to calculate the progressbar value from Timespan.Ticks rather than simply decrement.

Timer to count down in VB.Net 2010?

I'm trying to use a timer to count down from a specified time I choose with the time being separated into minutes and seconds using the format MM:SS and then stop when the time reaches 00:00.
So far I've used a previous answer that was found on here and modified it to the best of my knowledge with counting down although I've hit a snag in which when the timer successfully starts counting down, it's delayed and out of sync when counting down the minutes.
For example, counting down from 120 seconds;
02:00 >
02:59 >
02:58 >
02:57 >
02:56 >
02:55
And then when continuing to count down past 90 seconds under the same test;
02:30 >
01:29 >
01:28 >
01:27 >
01:26 >
01:25
When the countdown reaches 00 or 30 seconds, it incorrectly displays the minutes left and can't understand or figure out how to fix it.
Here is my code for my Counting Timer;
Private Sub tmrCountdown_Tick(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles tmrCountdown.Tick
SetTime = SetTime - 1
lblTime.Text = FormatTime(SetTime)
If SetTime = 0 Then
tmrCountdown.Enabled = False
End If
End Sub
Here is my code for the Function formatting the time;
Public Function FormatTime(ByVal Time As Integer) As String
Dim Min As Integer
Dim Sec As Integer
'Minutes
Min = ((Time - Sec) / 60) Mod 60
'Seconds
Sec = Time Mod 60
Return Format(Min, "00") & ":" & Format(Sec, "00")
End Function
And here is my code for the Form Load;
Private Sub frmSinglePlayer_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
'Setting the time.
SetTime = 120
lblTime.Text = FormatTime(SetTime)
tmrCountdown.Enabled = True
End Sub
I've set;
Dim SetTime As Integer
At the top of my Public Class so I am able to input a specified time into the countdown timer. This is probably something incredibly silly and I can't figure out what it is.
Any help is greatly appreciated and please bare in mind, I am a beginner at programming and get easily confused with large walls of code. (I can barely understand the Function as it is.)
Thank you for helping!
Play with this:
Public Class frmSinglePlayer
Private TargetDT As DateTime
Private CountDownFrom As TimeSpan = TimeSpan.FromMinutes(3)
Private Sub frmSinglePlayer_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
tmrCountdown.Interval = 500
TargetDT = DateTime.Now.Add(CountDownFrom)
tmrCountdown.Start()
End Sub
Private Sub tmrCountdown_Tick(sender As Object, e As System.EventArgs) Handles tmrCountdown.Tick
Dim ts As TimeSpan = TargetDT.Subtract(DateTime.Now)
If ts.TotalMilliseconds > 0 Then
lblTime.Text = ts.ToString("mm\:ss")
Else
lblTime.Text = "00:00"
tmrCountdown.Stop()
MessageBox.Show("Done")
End If
End Sub
End Class
Take a tested sample of countdown timer. Make the changes you need(ex the format of the time).
Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
SetTime = 70
AddHandler dtTimer.Tick, AddressOf dtTimer_Tick
dtTimer.Interval = New TimeSpan(0, 0, 1)
dtTimer.Start()
End Sub
Private Property SetTime As Integer
Private Sub dtTimer_Tick(sender As Object, e As EventArgs)
Dim iMinutes As Integer
Dim iSeconds As Integer
If SetTime = 0 Then
dtTimer.Stop()
txtTime.Text = "0:0"
Exit Sub
End If
SetTime -= 1
iMinutes = Math.Floor(SetTime / 60)
iSeconds = SetTime Mod 60
txtTime.Text = iMinutes & ":" & iSeconds
End Sub
Try this
'the amount of time to countdown from
Dim countDownFrom As New TimeSpan(0, 0, 10) 'ten seconds
'a Stopwatch to track how long running
Dim stpw As New Stopwatch
Private Sub Button1_Click(sender As Object, _
e As EventArgs) Handles Button1.Click
Timer1.Interval = 250 'how often to update display
Timer1.Start() 'start the display updater
stpw.Reset() 'restart the stopwatch
stpw.Start()
'or depending on version of .Net
'stpw.Restart
End Sub
Private Sub Timer1_Tick(sender As Object, _
e As EventArgs) Handles Timer1.Tick
If stpw.Elapsed <= countDownFrom Then
Dim toGo As TimeSpan = countDownFrom - stpw.Elapsed
lblTime.Text = String.Format("{0:00}:{1:00}:{2:00}", toGo.Hours, toGo.Minutes, toGo.Seconds)
Else
Timer1.Stop()
stpw.Stop()
End If
End Sub
your mistake in your original code is that you are using the MOD operater incorrectly.
'Minutes
Min = ((Time - Sec) / 60) Mod 60
'Seconds
Sec = Time Mod 60
At 2:00 you see 2:00 because:
Min = ((120-00) / 60 ) MOD 60 = 2 MOD 60 = 2
Sec = 120 MOD 60 = 0
At 1:59 you see 2:59 because
Min = (119 / 60) MOD 60 = 1.98 MOD 60 = 1.98 = 2
Sec = 119 MOD 60 = 59
After 31 seconds your minutes changes from 2 to 1 because
Min = (89 / 60) MOD 60 = 1.48 MOD 60 = 1.48 = 1
More simply:
Format((Math.Floor(lSeconds / 60)), "00") & ":" & Format((lSeconds Mod 60), "00")
Public SetTime As Integer = 0
Public Min As Integer = 0
Public Sec As Integer = 0
Public Decimaal As Decimal = 0
Public Function FormatTime(ByVal Time As Integer) As String
'Minutes
Min = Fix(SetTime / 60000)
'Decimaal
Decimaal = (SetTime / 60000) - Min
'Seconden
Sec = Fix(Decimaal * 60)
Return Format(Min, "00") & ":" & Format(Sec, "00")
End Function
Private Sub tmrCountdown_Tick(sender As Object, e As EventArgs) Handles tmrCountdown.Tick
SetTime = SetTime - 1000
lblCountdown.Text = FormatTime(SetTime)
tmrCountdown.Enabled = True
If SetTime = 0 Then
tmrCountdown.Enabled = False
End If
End Sub
You could just do
For i = 120 to 0 step -1
Console.writeline(i)
Next
But be aware it will instantly put them on the screen and it won't do it 1 at a time

Show Remaining time TimeSpan

I'm getting problems trying to show the remainig time of a operation
The problem is only with the remaining timer, I get a negative values...
This is a example of a operation of 10000 ms (10 secs):
So anyway if i remove the "-" char from the timespan the hour and the minute stills incorrects values...
Dim time_out as integer = 60000 ' 'Milisegundos
Dim StartTime As DateTime ' Tiempo inicio
Dim EndTime As DateTime ' Tiempo final
Dim ElapsedTime As TimeSpan ' Tiempo transcurrido
Dim RemainingTime As TimeSpan ' Tiempo restante
' Elapsed Time
#Region " Elapsed Time Function "
Public Function Print_Elapsed_Time()
If StartTime.ToString = "01/01/0001 0:00:00" Then
StartTime = Now
StartTime = StartTime.AddSeconds(-1)
End If
ElapsedTime = Now().Subtract(StartTime)
Return String.Format("{0:00}:{1:00}:{2:00}", CInt(Math.Floor(ElapsedTime.TotalHours)) Mod 60, CInt(Math.Floor(ElapsedTime.TotalMinutes)) Mod 60, CInt(Math.Floor(ElapsedTime.TotalSeconds)) Mod 60)
End Function
#End Region
#Region " Remaining Time Function "
Public Function Print_Remaining_Time()
If EndTime.ToString = "01/01/0001 0:00:00" Then
EndTime = Now
EndTime = EndTime.AddMilliseconds(Time_Out - 1000)
End If
RemainingTime = Now().Subtract(EndTime)
Return String.Format("{0:00}:{1:00}:{2:00}", CInt(Math.Floor(RemainingTime.TotalHours)) Mod 60, CInt(Math.Floor(RemainingTime.TotalMinutes)) Mod 60, CInt(Math.Floor(RemainingTime.TotalSeconds)) Mod 60).Replace("-", "")
End Function
#End Region
Here is an example of a countdown from 10 seconds using a timer and two labels
'example - countdown from 10 secs
Dim countdown As New TimeSpan(0, 0, 10)
Dim stpw As New Stopwatch
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If stpw.IsRunning Then
stpw.Stop()
Timer1.Stop()
Else
stpw.Stop()
stpw.Reset()
stpw.Start()
Timer1.Interval = 100
Timer1.Start()
End If
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
'label1 - elapsed time
'label2 - time remaining
If stpw.Elapsed <= countdown Then
Label1.Text = stpw.Elapsed.ToString
Label2.Text = (countdown - stpw.Elapsed).ToString
Else
stpw.Stop()
Label1.Text = countdown.ToString
Label2.Text = "00:00:00"
End If
End Sub
I think for the End Time you want :
RemainingTime = EndTime.Subtract(Now)
Otherwise, I'm not sure how you initialized these, but I made this change :
Dim StartTime As DateTime = DateTime.MinValue ' Tiempo inicio
Dim EndTime As DateTime = DateTime.MinValue ' Tiempo final
and also :
If StartTime = DateTime.MinValue Then ' ... etc '
but perhaps a flag or something is altogether a better way to signal a reset.