VB.NET DateTime from seconds only - vb.net

I would like to get a time (for example 03:00:03) feeding only the seconds, but nothing else.
Using the Microsoft.VisualBasic runtime, I could say
Dim sTimeRemaining As String = DateAndTime.TimeSerial(0, 0, iSecondsRemaining)
I would use this to show the user how long a download is still going to take.
Can somebody tell me how to do this without the Microsoft.VisualBasic runtime?
Thank you!

You could use
Dim sTimeRemaining As Date = New Date().AddSeconds(iSecondsRemaining)
Note that you should set Option Strict to On. Then your code wouldn't compile since DateAndTime.TimeSerial returns a Date and not a String. But it's a good thing because you are forced to build more robust and type safe code.
Perhaps it would also be better to use a TimeSpan instead of a Date in this case.
Dim seconds = TimeSpan.FromSeconds(iSecondsRemaining)

Related

Mid() usage and for loops - Is this good practice?

Ok so I was in college and I was talking to my teacher and he said my code isn't good practice. I'm a bit confused as to why so here's the situation. We basically created a for loop however he declared his for loop counter outside of the loop because it's considered good practice (to him) even though we never used the variable later on in the code so to me it looks like a waste of memory. We did more to the code then just use a message box but the idea was to get each character from a string and do something with it. He also used the Mid() function to retrieve the character in the string while I called the variable with the index. Here's an example of how he would write his code:
Dim i As Integer = 0
Dim justastring As String = "test"
For i = 1 To justastring.Length Then
MsgBox( Mid( justastring, i, 1 ) )
End For
And here's an example of how I would write my code:
Dim justastring As String = "test"
For i = 0 To justastring.Length - 1 Then
MsgBox( justastring(i) )
End For
Would anyone be able to provide the advantages and disadvantages of each method and why and whether or not I should continue how I am?
Another approach would be, to just use a For Each on the string.
Like this no index variable is needed.
Dim justastring As String = "test"
For Each c As Char In justastring
MsgBox(c)
Next
I would suggest doing it your way, because you could have variables hanging around consuming(albeit a small amount) of memory, but more importantly, It is better practice to define objects with as little scope as possible. In your teacher's code, the variable i is still accessible when the loop is finished. There are occasions when this is desirable, but normally, if you're only using a variable in a limited amount of code, then you should only declare it within the smallest block that it is needed.
As for your question about the Mid function, individual characters as you know can be access simply by treating the string as an array of characters. After some basic benchmarking, using the Mid function takes a lot longer to process than just accessing the character by the index value. In relatively simple bits of code, this doesn't make much difference, but if you're doing it millions of times in a loop, it makes a huge difference.
There are other factors to consider. Such as code readability and modification of the code, but there are plenty of websites dealing with that sort of thing.
Finally I would suggest changing some compiler options in your visual studio
Option Strict to On
Option Infer to Off
Option Explicit to On
It means writing more code, but the code is safer and you'll make less mistakes. Have a look here for an explanation
In your code, it would mean that you have to write
Dim justastring As String = "test"
For i As Integer = 0 To justastring.Length - 1 Then
MsgBox( justastring(i) )
End For
This way, you know that i is definitely an integer. Consider the following ..
Dim i
Have you any idea what type it is? Me neither.
The compiler doesn't know what so it defines it as an object type which could hold anything. a string, an integer, a list..
Consider this code.
Dim i
Dim x
x = "ab"
For i = x To endcount - 1
t = Mid(s, 999)
Next
The compiler will compile it, but when it is executed you'll get an SystemArgumenException. In this case it's easy to see what is wrong, but often it isn't. And numbers in strings can be a whole new can of worms.
Hope this helps.

Format number with leading zeroes in .NET 2.0

I have problem to format numbers and convert it to string with leading zeroes when application uses NET framework 2.0 with Visual Basic.
I try:
Dim myNum = 12
Dim myStr as String
Dim myStr = myNum.ToString("0000")
or
Dim myStr = myNum.ToString("D4")
... in order to get wanted string: 0012
Please help to solve this.
You have an old version of Visual Studio, one that doesn't have Option Infer yet. Or it isn't turned on. That makes the myNum identifier a variable of type Object.
So your code tries to call the Object.ToString() method. Which does not have an overload that takes an argument. The compiler now tries to make hay of your code and can only do so by treating ("0000") or ("D4") as an array index expression. Indexing the string that's returned by Object.ToString(). That has pretty funny side effects, to put it mildly. A string like "0000" is not a valid index expression, the compiler generates code to automatically convert it to an Integer. That works for "0000", converted to 0 and the result is a character, just "1"c. Converting "D4" to an integer does not work so well of course, that's a loud Kaboom!
The solution is a very simple one, just name the type of the variable explicitly:
Dim myNum As Integer = 12
Dim myStr = myNum.ToString("D4") '' Fine
VB.NET's support for dynamic typing is pretty in/famous. Meant to help new programmers getting started, it in fact is an advanced technique given the myriad ways it can behave in very unexpected ways.
The universal advice is always the same. Let the compiler help you catch mistakes like this. Put this at the top of your source code file:
Option Strict On

String.Format on a datetime field

I am trying to get the time part (24h) of a datetime field
Dim Dt as datetime =#1/1/1900 8:00:00 PM#
Dim Str as string = String.Format(Dt, "HH:mm")
Which returns "1/1/1900 8:00:00 pm"
What am i doing wrong here?
Use the overridden ToString that exists on DateTime:
Dt.ToString("HH:mm")
what was wrong with the first option?
The String.Format() method has 5 overloads, none of which have two arguments that can take a DateTime as the first argument. What happens next depends on which way you like to use Visual Basic. You can put this at the top of your source code file:
Option Strict On
and the VB.NET compiler gets picky about your code. You'll now get a compile time error:
Overload resolution failed because no accessible 'Format' can be called with these arguments
Clearly you have it off so it tries to make to make tea from the leaves you give it. There is exactly one overload of String.Format() that can still be called, it the Format(String, Object) overload. With was intended to write code like this:
Dim str = String.Format("The time is {0:HH:mm}", Dt)
A feature called composite formatting. In your case, this method can only be called if the VB.NET compiler first converts the DateTime to a string automatically. In effect you'll call:
Dim str = String.Format("1/1/1900 8:00:00 pm", "HH:mm")
Which doesn't do what you hoped it does.
It is usually best to learn VB.NET coding by having the Option Strict always turned on. And only turn it off when you know the language well enough to survive accidents like this. You can tell Visual Studio to always turn the option on. Tools + Options, Projects and Solution, VB Defaults and change the Option Strict selection to On.
You could try using Date.ToString:
http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.90).aspx

VB.net Hour(Now()) Not Working

I am trying to make a vb.net program which at a specific time that the user has chosen, the code will excecute. To do this, I need to check every minute to check every minute if the hour and minute the user has entered are matching to the current time (unless there is a better way to do this). I tried to use
Dim CurrentHour As Integer = Hour(Now())
But the program gives me an error message saying,
Expression is not an array or method, and cannot have an argument list
I am going to use a Do Loop to check, but of course to see if the two are matching, I need the current Hour and Minute
Your code is correct. What you need to watch our for is stuff like this:
Dim Now As Date
Dim CurrentHour = Hour(Now())
Which produces error BC30471: Expression is not an array or a method, and cannot have an argument list.
You see the problem by now perhaps, the Now variable hides the Now function. The compiler now gets confuzzled, it doesn't understand why the parentheses are present. And correctly complains that Now is not an array and not a method. It isn't, not anymore.
Other than renaming the variable, you can also solve it by giving a more complete name:
Dim CurrentHour = Hour(DateAndTime.Now())
Although that gets to be fairly obscure, using DateTime.Now instead is the .NET way instead of the Basic way.
You should use the native DateTime properties:
Dim CurrentHour As Integer = Now().Hour
If you want to use the Hour method, you may need to fully qualify it to be:
Microsoft.VisualBasic.Hour(Now())
because Hour is most likely a property or method elsewhere in your application.
Dim Inputtime As DateTime
if Inputtime = Date.Now.Hour Then
MsgBox("Success!")
End If
I wouldn't use a do loop as it will consume all of the memory for the program. I would go with a timer that ticks once every miunute. and have it fire this sub routine.
Task Scheduler is an option. I rather use Marshal.FinalReleaseComObject then the loop in the bottom of the code, and GC.Collect needs to be called again after GC.WaitForPendingFinalizers()

How do you convert a string into base64 in .net framework 4

So I've been going around the internet looking for a way to convert regular text(string) into base64 string and found many solutions. I'm trying to use:
Dim byt As Byte() = System.Text.Encoding.UTF8.GetBytes(TextBox1.Text)
TextBox2.Text = convert.ToBase64String(byt)
but it end up with an error saying
'ToBase64String' is not a member of 'System.Windows.Forms.Timer'.
What do I do to fix this? Or if there's a better way to code it please help.
Use System.Convert.ToBase64String(byt). Otherwise the timer is picked up as the innermost matching name.
Not the best name for a timer btw.