Reputation: 33
Please see the below code:
Dim dtEstComplDate As Date
Try
dtEstComplDate = "08-mar-16"
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
If I set my computers local format as English (united states), '08-mar-16'
gets assigned to dtEstComplDate
as #3/82016#
Now, If I change my computers format to Italian, this assignment results in the following exception:
"Conversion from string "08-mar-16" to type 'Date' is not valid."
I tried with 08-mrz-16
with italian setting. It did not work.
Upvotes: 0
Views: 510
Reputation: 9510
I hope below example will help you to understand .. why these happend.. when you changing region in regional setting .. same thing happening here by dot net code ...
Dim dtEstComplDate As Date
Try
'Will be the country name you set using datetimesetting
MessageBox.Show(System.Threading.Thread.CurrentThread.CurrentCulture.Name)
Dim ukCulture As System.Globalization.CultureInfo
Dim itCulture As System.Globalization.CultureInfo
ukCulture = New Globalization.CultureInfo("en-GB")
itCulture = New Globalization.CultureInfo("it-IT")
Dim strDate = "08-mar-16"
'forcing to use uk culture when converting string to date
System.Threading.Thread.CurrentThread.CurrentCulture = ukCulture
dtEstComplDate = strDate
MessageBox.Show(dtEstComplDate)
'forcing to use italian culture when converting string to date
System.Threading.Thread.CurrentThread.CurrentCulture = itCulture
dtEstComplDate = strDate
MessageBox.Show(dtEstComplDate)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Upvotes: 0
Reputation: 97
try this its more simple to convert any to date
MsgBox(CDate("01/02/16").ToString("yyyy-MM-dd"))
the cdate function will convert your text to date
Upvotes: 0
Reputation: 460098
The reason is that mar
is the abbreviation for the month march in english not in italian.
Don't use strings to initialize dates. Instead you should change Option Strict
to On
. Then you'll learn a lot about .NET methods and types and how to write type safe code. If you want to initialize a Date you can use the constructor: dtEstComplDate = New Date(2016, 3, 8)
.
If you really have to parse a string to Date
use Date.Parse
/Date.TryParse
or Date.ParseExact
/Date.TryParseExact
:
dtEstComplDate = Date.ParseExact("08-mar-16", "dd-MMM-yy", DateTimeFormatInfo.InvariantInfo)
I'm using InvariantInfo
because it's derived from the english format.
Upvotes: 5