My application works for systems in the US, however for some other regions it is returning this error:
"Conversion from string "8/31/2016" to type 'Date' is not valid".
Here is one code sample:
dte_BuildDate_Current = CDate(str_BuildDate_Current)
Any thoughts on addressing this would be appreciated.
Use DateTime.Parse method where you can pass specific culture you expect date string to be in.
Dim dateAsString = "8/31/2016"
Dim culture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US")
Dim currentDate = DateTime.Parse(dateAsString, culture)
Actually I would suggest to use <type>.Parse or <type>.TryParse method over CDate, CInt or others.
Parse methods are more explicit about their intentions, where CDate or others similar trying to guess your intentions and do a lot of unnecessary work.
Related
I am working on vb.net application
am getting date like this :
recevdate = rs("ITIReceiveddate")
my recevdate format is like this : 2/27/2016 month/date/year
i want to convert like this : date.month.year 27.2.2016
so i wrote code like this :
Dim dt as string = DateTime.ParseExact(recevdate, "dd.MM.yyyy", Nothing)
but its getting error ..
What is wrong with my code? how i can rectify this issue?
any help is very appreciable..Thanks
DateTime.ParseExact returns a DateTime, not a string. Your project is setup with the Option Strict set to Off and this enables this kind of automatic conversions. But it is, as usual, a trap waiting to kick on unsuspecting programmers.
To execute correctly you need
Dim recevdate = "2/27/2016"
Dim dt As DateTIme = DateTime.ParseExact(recevdate, "M/d/yyyy", Nothing)
Dim formattedString = dt.ToString("d.M.yyyy")
Console.WriteLine(formattedString)
Notice that you have an error also in your formatted mask for parsing the date. If your date has only one digit for months or one digit for days then you need just one M and one d both on the parsing and in the formatting back to string
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
I have a datetime that looks like this:
201210120956
ccyyMMDDhhmm
When I try this:
Dim convertedDate As Date = Date.Parse(DateString)
Return convertedDate
I get back this:
#10/12/2012#
I'm losing the time on it.
I've read this convert string to datetime vb.net but when I use datetime.ParseExact() I get:
cannot resolve symbol 'ParseExact'
Is there a way to convert this to a date time without using substring? A straight conversion?
Pass the decode pattern to ParseExact
Dim d as string = "201210120956"
Dim dt = DateTime.ParseExact(d, "yyyyMMddhhmm", Nothing)
ParseExact is available only from Net FrameWork 2.0.
If you are still on 1.1 you could use Parse, but you need to provide the IFormatProvider adequate to your string
You can try with ParseExact method
Sample
Dim format As String
format = "d"
Dim provider As CultureInfo = CultureInfo.InvariantCulture
result = Date.ParseExact(DateString, format, provider)
As an alternative, if you put a space between the date and time, DateTime.Parse will recognize the format for you. That's about as simple as you can get it. (If ParseExact was still not being recognized)
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)
I seem to have a date formatting problem every day!
I am querying a table and am getting a date back in the format dd/mm/yyyy (as a string btw). Brilliant! thats what I want. But, now I want to convert that string to a date so i can do
dim dayNumber as integer = day.DayOfWeek
But when I convert it to a date it changes it to #m/dd/yyyy#. AHHHH! how can I change this?
here is my code i've tried
Dim ActivityDate As String
If dt.Rows(i)("Date") Is DBNull.Value Then
ActivityDate = ""
Else
ActivityDate = dt.Rows(i)("Date")
End If
Dim ci As New System.Globalization.CultureInfo("en-CA")
Dim theDate As Date = Date.Parse(ActivityDate, ci)
Dim day As Integer = theDate.DayOfWeek
Cheers
Brilliant! thats what I want
That's not what you want. It is the worst possible format for a date because it is so horribly ambiguous. Date string formats depend on the current culture. "4/1/2010" is Unicorn day at SO, it is day in January in Europe. "#4/1/2010#" is a legacy VB6 format.
Always store dates in a DateTime in your code. Always store dates in a database column type of datetime in your dbase. There is never any ambiguity and you'll have an easy time with the DateTime members to manipulate dates.
If you convert the string to a date, you can always output it back to the original format using a custom format string: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
The correct solution here (at least until you tell us why this isn't possible) is to update your database to use a datetime column type rather than a varchar. Now we also know that this column has no NULL values, because otherwise you'd be complaining about exceptions on your Date.Parse() call. After applying both those sentences, you can trim all that code down to a simple one-liner:
Dim day As Integer = DirectCast(dt.Rows(i)("Date"), DateTime).DayOfWeek
May I also ask why you're looping through the table row by row? I've worked in a shop where that was the norm, but since I've left there I've run in to alternatives and more and more I'm coming to find looping through a datatable as just wrong. It's an older imperative coding style, and generally you want to go for a declarative coding style.
Are you parsing it like this:
Dim newDate as DateTime = DateTime.Parse(myDate)
If the culture of your system does not use that date format, then you should get that date string as an actual date:
' canadian date format is dd/mm/yyyy
Dim ci As New System.Globalization.CultureInfo("en-CA")
Dim theDate As Date = Date.Parse("13/04/2010", ci)
Make sure you specify an exact parse format like so:
Console.WriteLine(DateTime.ParseExact("17/12/2010", "dd/mm/yyyy", null));
I am not sure what the last parameter is but it is safe to ignore it.
I'm guessing that you are seeing the #m/dd/yyyy# in the debugger, like this screenshot below. Don't worry!
A Date variable isn't stored as a string. The debugger has to convert your Date into a string to display it, and it insists on showing dates in #m/dd/yyyy# format. But that doesn't have any effect on the runtime behaviour of your program.
Screenshot of Visual Studio Debugger http://img707.imageshack.us/img707/6205/debugger.gif