String.Format on a datetime field - vb.net

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

Related

How to convert Timer.Enabled to type Control

After converting code from VB6 to VB.NET I got the following resultant code:
Designer Form Code:
Public WithEvents Timer1 As Microsoft.VisualBasic.Compatibility.VB6.TimerArray
Me.Timer1 = New Microsoft.VisualBasic.Compatibility.VB6.TimerArray(components)
Code Implementation:
Private Function GetBaseControl(ByRef a_type As String) As System.Windows.Forms.Control Implements GetBaseControl
Select Case a_type
Case "Web"
GetBaseControl = ctBrowser1(0)
Case "Timer"
GetBaseControl = Timer1(0)
End Select
End Function
Here the Error I've received:
Value of type 'Boolean' cannot be converted to 'System.Windows.Forms.Control' at Line GetBaseControl = Timer1(0).
That works fine in VB6 Though !!
If this ever worked in VB6, the code was following some very poor practices to return the Boolean Enabled instead of the actual Timer component. It implies, at minimum, that Option Strict was off, and that's really bad.
In this case, Timers in .Net are no longer considered Controls at all. Instead, they are Components. You'll want to re-think how this code functions. An example of how the code is used might let us recommend a different (better) approach to the problem.
In this case, I suspect re-thinking this to use overloaded methods (which was not idiomatic for vb6) will produce better results, especially with regards to preserving type safety rather than passing strings around.
Note: this answer made more sense before the question was edited the next day

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

VB.NET DateTime from seconds only

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)

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()

datediff help in vb.net

Hey all i have 2 dates that i need to see the days that are different.
Problem being is that the server date is not in the normal MM/DD/YYYY format. It is in the format YYYYMMDD.
I've tried the following:
Dim curDate As Date = Format(Now, "yyyyMMdd")
Dim srDate As Date = dr(6)
Dim M As Long = DateDiff(DateInterval.Weekday, curDate, srDate)
The curDate has the error of:
Conversion from string "20110325" to type 'Date' is not valid.
Any help would be great! :o)
David
Try not to hammer a square string peg into a round date hole, that just has way too many ways to break your mallet. The Now function already returns a date:
Dim curDate As Date = Now.Date
Option Strict On at the top of the source code file helps you find these kinds of mistakes.
If you get the string from the server (pray you don't) then use ParseExact() to convert the date:
Dim curDate As Date = Date.ParseExact(serverValue, "yyyyMMdd", Nothing)
Why are you formatting Now like that? You could just do this:
Dim curDate As Date = DateTime.Now.Date
As the other posters have said, you don't need to format DateTime.Now.
But there's something else going wrong here: Format returns a string, and you're trying to assign that to a Date. It's trying to implicitly convert a string, and failing.
In future, when you do have a date-string like "yyyyMMdd" to turn into a DateTime type, use DateTime.Parse
Your problem is the first line; it seems you have Option Strict off in your project (FOR SHAME!), as it would otherwise not compile at all.
Format(Now, "yyyyMMdd") will produce the current date formatted in that manner as a string. The trouble is that you're attempting to assign that output (the string) to a Date variable. Because you have Option Strict off, the compiler indicates this conversion implicitly, and the runtime is attempting to convert your non-standard date string back into a date. This is what's failing.
Changing as little as possible about your code, it should read:
Dim curDate As Date = Now.Date
Dim srDate As Date = DateTime.ParseExact(dr(6).ToString(), "yyyyMMDD", CultureInfo.InvariantCulture).Date
Dim M As Long = DateDiff(DateInterval.Weekday, curDate, srDate)
Step 0: TURN OPTION STRICT ON
There's no reason that new code should be written with this option turned off. There's too much potential for runtime errors that are easily caught at compile time (like this one) with it off. It's a feature that should be banished from the language entirely.
Step 1: Adopt standard .NET types and functions
While this isn't required, it will make your code more readable to other developers and other developers' code more readable to you. Things like Format, DateDiff, Now, etc. are all VB-specific functions that exist primarily to make it easier for classic VB6 applications to be ported over to .NET. Unless there's a particular reason to use the language-specific versions, it's a good idea to use standard .NET functions instead.
Firstly:
"MM/DD/YYYY" is not normal in most of the world, only North America.
China uses "YYYY-MM-DD".
Europe uses "DD/MM/YYYY"
Secondly, if you are parsing a known date format, you can pass a format string to DateTime.Parse. In your case that is what you need to do.
Try
Dim curDate As Date = Now
Dim srDate As Date = mid(dr(6),5,2) & "/" & right(dr(6),2) & "/" & left(dr(6),4)