Formatting Time (HH:MM:SS) - vb.net

I'm taking values from Numeric Ups and Downs for Hours, Minutes and Seconds.
The problem is that, for example, if the time for example is 9.15 am it will show as 9:15:0
What I want to do is format them so if any of the values(Hours, Minutes or seconds) is less than 10, it will add a 0 before the number so as the number shows as 09:15:00.
What I tried is this but it does not work:
Sub BtnSetClick(sender As Object, e As EventArgs)
lbl8.Visible = True
Dim nmTime As String = nmHour.Value.ToString + nmMin.Value.ToString + nmSec.Value.ToString
lblST.Text.Format(nmTime.ToString, "HH:MM:SS")
lblST.Text = (nmTime)
lblST.Visible = True
End Sub

You seem to be doing it a bit backward by converting everything to string multiple times, try something like this:
Dim ts As new TimeSpan(CInt(nmHour.Value), CInt(nmMin.Value), CInt(nmSec.Value))
lblST.Text = ts.ToString("HH:MM:SS")
The documentation for TimeSpan.ToString is useful.
Edit: Updated the code to reflect Tim's comment about datatype.

Try this:
Sub BtnSetClick(ByVal sender As Object, ByVal e As EventArgs)
lbl8.Visible = True
Dim nmTime As String = nmHour.Value.ToString().PadLeft(2, '0') + nmMin.Value.ToString().PadLeft(2, '0') + nmSec.Value.ToString().PadLeft(2, '0')
lblST.Text = nmTime
lblST.Visible = True
End Sub

try using the TimeSpan object, it should do all the hard work for you!
Dim nmTime As New TimeSpan(nmHour.Value, nmMin.Value, nmSec.Value)
lblST.Text = nmTime.ToString
lblST.Visible = True

Related

Same number is generated in RNG in VB.NET

I am attempting to make a random number generator in VB 16 in Visual Studio, but every time I run this I keep getting 71, I've tried making it public, sharing it and several other things, but it won't work. I am trying to make a program that has the user guess a randomly generated number, and continue guessing until they get it, but for some reason the exact same number is chosen each time. It won't work properly specifically in window app forms. How do I get a random number each time?
Public Shared Randomize()
Dim value As Integer = CInt(Int((100 * Rnd()) + 1))
Public Sub EnterBtn_Click(sender As Object, e As EventArgs) Handles EnterBtn.Click
Dim entervalue As String = EnterTxt.Text
Dim chances As Integer
Select Case entervalue
Case > value
ResTxt.Text = "Too big"
chances += 1
Case < value
ResTxt.Text = "Too small"
chances += 1
Case = value
ResTxt.Text = "Well done, you got it in " & chances & " tries"
End Select
End Sub
You were close! Here's a working example modifying your original logic:
Private random As Random = New Random()
Private value As Integer
Private chances As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
value = random.Next(1, 100)
chances = 0
End Sub
Private Sub EnterBtn_Click(sender As Object, e As EventArgs) Handles EnterBtn.Click
Select Case EnterTxt.Text
Case > value
chances += 1
ResTxt.Text = "Too big"
Case < value
chances += 1
ResTxt.Text = "Too small"
Case = value
chances += 1
ResTxt.Text = "Well done, you got it in " & chances & " tries"
'and reset for next attempt
value = random.Next(1, 100)
chances = 0
End Select
End Sub
Since your code is not correct it is hard to pinpoint the problem. It is also not clear what the code is supposed to do.
Try this
Private Shared PRNG As New Random ' add this
value = PRNG.Next(1, 101)'this will set value to a random number between 1 and 100 inclusive
Here's some skeleton code for you:
Dim rnd As New Random()
For i as Integer = 0 to 10
Console.WriteLine("{0,15:N0}", rnd.Next())
Next
Notice the rnd.Next() thing. Hope it helps.

I'm having difficulty calculating time differences in Visual Basic [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Layout of Calculator
I am trying to build a program that calculates times differences in minutes. I do this by subtracting the start time from the finish time. I have four text boxes, two of which are for the time unit of hours (h), and the other two are for minutes (m).
a is the starting time in hours and c is the finish time in hours. They are being multiplied by 60 to convert the hours to minutes. I want to calculate the time difference between 5:40pm and 7:15pm but some how end up with 567 when the answer should be 95.
This is not a homework task, I'm a lazy learner driver in Australia who wants to create a simple program that calculates the time of a journey in minutes.
Can somebody please tell me what I'm doing wrong?
Here is my code:
Public Class Calc
Dim Product
Dim a, b, c, d As Integer
Private Sub Enter_Click(sender As Object, e As EventArgs) Handles Enter.Click
a = Val(TextBox1.Text) * 60
b = Val(TextBox2.Text)
c = Val(TextBox3.Text) * 60
d = Val(TextBox4.Text)
Product = (c - a + d - b)
Time.Text = ("Driving Time: " & Product)
End Sub
End Class
I wasn't going to post this but I couldn't let the use of TimeSerial by Dy.Lee go unanswered. This code uses reasonable variable names, uses the correct type for time periods, i.e. TimeSpan, and also compiles with Option Strict On, which it should pretty much always be. I'd get rid of that Val usage too but I couldn't be bothered here.
Private Sub Enter_Click(sender As Object, e As EventArgs) Handles Enter.Click
Dim startHours = CInt(Val(TextBox1.Text))
Dim startMinutes = CInt(Val(TextBox2.Text))
Dim endHours = CInt(Val(TextBox3.Text))
Dim endMinutes = CInt(Val(TextBox4.Text))
Dim startTime As New TimeSpan(startHours, startMinutes, 0)
Dim endTime As New TimeSpan(endHours, endMinutes, 0)
Dim timeDifference = endTime - startTime
Time.Text = ("Driving Time: " & timeDifference.TotalMinutes)
End Sub
EDIT: It also declares variables in the appropriate place, i.e. in the method they're being used in. If you're using those same variables elsewhere then you'd have to stick with fields but I'm guessing that you're not doing so.
EDIT: Here's a version without the dodgy Val calls and some proper validation. You could combine all the If statements into one but separating them allows you to display different messages based on the type of issue.
Private Sub Enter_Click(sender As Object, e As EventArgs) Handles Enter.Click
Dim startHours As Integer
Dim startMinutes As Integer
Dim endHours As Integer
Dim endMinutes As Integer
If Integer.TryParse(TextBox1.Text, startHours) AndAlso
Integer.TryParse(TextBox2.Text, startMinutes) AndAlso
Integer.TryParse(TextBox3.Text, endHours) AndAlso
Integer.TryParse(TextBox4.Text, endMinutes) Then
If startHours < 24 AndAlso
startMinutes < 60 AndAlso
endHours < 24 AndAlso
endMinutes < 60 Then
Dim startTime As New TimeSpan(startHours, startMinutes, 0)
Dim endTime As New TimeSpan(endHours, endMinutes, 0)
If startTime < endTime Then
Dim timeDifference = endTime - startTime
Time.Text = ("Driving Time: " & timeDifference.TotalMinutes)
Else
'Notify user of invalid input.
End If
Else
'Notify user of invalid input.
End If
Else
'Notify user of invalid input.
End If
End Sub
#PaulHebert pointed out to me that I needed to swap around textbox 3 & 4 because I was treating the wrong fields as hours. The math had made sense in my head so I probably overlooked a rather simple yet inconvenient mistake. I want to thank everyone who tried to help :) Merry Christmas!
Your math is wrong you are subtracting the hours and then adding them to the difference of minutes. You need to get the total number of minutes since midnight from each time and then subtract those. Then get the absolute value so you don't have negative minutes
Private Sub Enter_Click(sender As Object, e As EventArgs) Handles Enter.Click
a = Val(TextBox1.Text) * 60
b = Val(TextBox2.Text)
c = Val(TextBox3.Text) * 60
d = Val(TextBox4.Text)
Product = Math.Abs((c +d) - (a + b))
Time.Text = ("Driving Time: " & Product)
End Sub
Try using this code
Private Sub Enter_Click(sender As Object, e As EventArgs) Handles
a = CInt(Trim(TextBox1.Text)) * 60
b = CInt(Trim(TextBox2.Text))
c = CInt (Trim(TextBox3.Text)) * 60
d = CInt(Trim(TextBox4.Text))
Product = (c + d) - (a + b)
Time.Text = ( "Driving Time: " & Product)
End Sub
Also make sure that the text boxes are properly arranged. Text box 1 should come first followed by the others.

Need A Timer To Fire At Specific Time And Every 5 Minutes Until Job Complete

I need help setting up a specific type of timer for my application. My scenario is this:
I want to run a timer at a specific time of day (say 4:00AM). That timer then executes a number of different events that each go off and grab data from a database and process it (using background workers). All the different events take different times to finish (could be 30 seconds, could be 5 minutes). I want to continuously enter the timer event every 5 minutes thereafter checking if all events have finished. If so, stop the timer and restart it again at 4:00AM the next morning and so on.
So the process would look like this:
04:00AM - Start Timer and initiate background workers
04:05AM - Check again to see if processes have completed (if so, stop timer)04:10AM - Check again to see if processes have completed (if so, stop timer)
And so on....
I already have my background worker code that processes my database information. So I just need help setting up the timer.
So far I have the following in my Tick event:
Private Sub tmr_Maintenance_Tick(sender As Object, e As EventArgs) Handles tmr_Maintenance.Tick
Dim CurrentTime As Date
Dim CurrHour As Integer
CurrentTime = DateTime.Now
CurrHour = CurrentTime.Hour
'Automatic Sales Import
With My.Settings
If CurrHour = 4 Then
If Not .Maintenance_Ran Then
CreateLog("Maintenance Started")
If Not .Yesterdays_Sales_Imported Then
CreateLog("Importing Yesterday's Sales From Portal")
If Not YesterdaysSales_Worker.IsBusy Then YesterdaysSales_Worker.RunWorkerAsync()
End If
If Not .WTD_Sales_Imported Then
CreateLog("Importing Week To Date Sales From Portal")
If Not WeekToDateSales_Worker.IsBusy Then WeekToDateSales_Worker.RunWorkerAsync()
End If
If Not .LW_Sales_Imported Then
CreateLog("Importing Last Week Sales From Portal")
If Not LastWeekSales_Worker.IsBusy Then LastWeekSales_Worker.RunWorkerAsync()
End If
If .Yesterdays_Sales_Imported = True And .WTD_Sales_Imported = True And .LW_Sales_Imported = True Then
.Maintenance_Ran = True
End If
End If
Else
.Maintenance_Ran = False
End If
End With
My.Settings.Save()
End Sub
Any help appreciated thanks.
Here's a basic framework you can start from:
Public Class Form1
Private Enum MaintenanceState
WaitingToStart
Started
End Enum
Private Target As DateTime
Private state As MaintenanceState = MaintenanceState.WaitingToStart
Private MaintenanceTime As New TimeSpan(4, 0, 0) ' 4:00 am
Private WaitingInterval As New TimeSpan(0, 5, 0) ' Five minutes
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Target = GetNextMaintenanceTarget(MaintenanceTime)
tmr_Maintenance.Interval = 1000
tmr_Maintenance.Start()
End Sub
Private Sub tmr_Maintenance_Tick(sender As Object, e As EventArgs) Handles tmr_Maintenance.Tick
' optionally display time remaining until next target
Dim ts As TimeSpan = Target.Subtract(DateTime.Now)
Label1.Text = ts.ToString("hh\:mm\:ss")
' see if we've hit the target
If DateTime.Now >= Target Then
tmr_Maintenance.Stop()
Select Case state
Case MaintenanceState.WaitingToStart
' ... start all the jobs ...
state = MaintenanceState.Started
Target = DateTime.Now.Add(WaitingInterval)
Case MaintenanceState.Started
' ... check to see if the jobs are all done ...
If Not AllJobsCompleted Then
Target = DateTime.Now.Add(WaitingInterval)
Else
state = MaintenanceState.WaitingToStart
Target = GetNextMaintenanceTarget(MaintenanceTime)
End If
End Select
tmr_Maintenance.Start()
End If
End Sub
Private Function GetNextMaintenanceTarget(ByVal time As TimeSpan) As DateTime
Dim dt As DateTime = DateTime.Today.Add(time)
If DateTime.Now > dt Then
dt = dt.AddDays(1) ' already past target time for today, next start is tomorrow
End If
Return dt
End Function
End Class
Instead of firing your timer every second and checking the current hour (which seems problematic anyway) why not calculate how many milliseconds until 4 am and set the timer to fire at that time?
Dim timer = New Timer()
timer.Interval = MillisecondsUntilNextFourAm
...
Function MillisecondsUntilNextFourAm() As Integer
Dim now = DateTime.Now()
If now.Hour < 4 Then
Return (TimeSpan.FromHours(4) - now.TimeOfDay).TotalMilliseconds
Else
Return (TimeSpan.FromHours(28) - now.TimeOfDay).TotalMilliseconds
End If
End Function
You could do something similar if you then want the timer to fire again in 5 minutes. I would set the timer's AutoReset property to False and call Start each time after setting the interval.

String manipulation: Display all characters to the left of "|" delimiter

I am in need of help. I have a combobox that displays the following results
A123456|Employee A
I then want to take the first 6 characters and place that result on a cell, so I worked out the following code:
Private Sub cmbSelectEmployee_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbSelectEmployee.SelectedIndexChanged
Dim employeeInfo As String = cmbSelectEmployee.Text
Dim employeeID = Microsoft.VisualBasic.Left(employeeInfo, 6)
Globals.calCalculationSheet.Range("B36").Value = employeeID
End Sub
Works perfect, only that now I realized that the 6 digits left of the "|" will not always be 6. Sometimes is 5, other times may be 10. So now I need to display all characters to the left of "|"
I used the Split("|"c)), but I could not figure out how to then place the left characters into a variable.
You can use String.IndexOf() to find the index of a character in a string:
Dim employeeID = Microsoft.VisualBasic.Left(employeeInfo, employeeInfo.IndexOf("|"))
Note that String.IndexOf() will return -1 if the string does not contain the character that you request. If you are not sure that your string will always contain the | you will need to test the return value of String.IndexOf().
Please try this.
Private Sub cmbSelectEmployee_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbSelectEmployee.SelectedIndexChanged
Dim employeeInfo As String = cmbSelectEmployee.Text
Dim employeeID = employeeInfo.Split("|")(0)
Globals.calCalculationSheet.Range("B36").Value = employeeID
End Sub

Twitterizer - TwitterStatusCollectionResponse ResponseObject nothing

I am trying to get the timeline of my user account so I can post the tweets on our website. However, the TwitterStatusCollectionResponse ResponseObject is always nothing. The Content property has what looks to be a valid json response. The Result property is "Unknown". Here is my code:
Dim tokens As New OAuthTokens()
tokens.AccessToken = "XX"
tokens.AccessTokenSecret = "XX"
tokens.ConsumerKey = "XX"
tokens.ConsumerSecret = "XX"
Dim options As New SearchOptions()
options.PageNumber = 2
options.NumberPerPage = 2
Dim timelineOptions As New TimelineOptions
timelineOptions.IncludeRetweets = False
timelineOptions.Count = 5
Dim statusCollectionResponse As TwitterResponse(Of TwitterStatusCollection) = TwitterTimeline.HomeTimeline(tokens, timelineOptions)
'this next line errors.....
For Each status In statusCollectionResponse.ResponseObject
next
Bet you got this version with nuget? There have been problems with twitterizer via nuget for a while, mostly due to incompatible json.net versions. I bet if you need it now you can get an older json.net and fix the issue for now.
Looks like this is a known bug that the author is fixing.
http://forums.twitterizer.net/viewtopic.php?f=9&t=3721&p=5568&hilit=TwitterResponse+Of+TwitterStatusCollection+#p5568
I"ll wait for the next release.
Just wrote this little test, it looks like it works just fine.
You can target the user using the UserId in the UerTimelineOptions
good luck.
'Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Dim s As New UserTimelineOptions
' s.Count = 3000
' s.UseSSL = True
' s.APIBaseAddress = "http://api.twitter.com/1/"
' s.IncludeRetweets = False
' s.UserId = 24769625
' Dim T As TwitterResponse(Of TwitterStatusCollection) = TwitterTimeline.UserTimeline(tokens, s)
' For Each Tweet As TwitterStatus In T.ResponseObject
' Console.WriteLine(Tweet.User.ScreenName & ": " & Tweet.Text)
' Next
'End Sub