Converting String into DateTime Format (in a Globalization Manner)

microkarl

Well-known member
Joined
Apr 22, 2004
Messages
82
Location
Morristown, NJ
Hello all,
I have a question about convert strings into dataTime format (in a globalization manner). Consider I have the following code:

Code:
Dim strMonth As String = "12"
Dim strDay As String = "30"
Dim strYear As String = "2005"

strTime = strMonth & "/" & strDay & "/" & strYear
dtmTime = CDate(strTime)
dtmTime.ToString("MM/dd/yyyy")

The code would work and return "12/30/2005" if we are using United Sates DateTime Format (Regional Settings in Control Panel). However, if we choose some other culture, say Britsh, their regional datetime string format is "DD/mm/yyyy", so the above code would crash because CDate() converts a string to datetime based on the setting from the regional settings. So, my question is that is there any graceful way to handle situation like this easily?

I did some research on Google but I found out theres no single function to do it, or maybe I am missing somthing... Please let me know if you guys have any solutions...

Thanks,
Carl
 
My limited experience has shown two issues with dates. Parsing a string and sending a date to a database.

When parsing or displaying a string, I like to use the built in functions such as ToShortDateTimeString or other methods of a DateTime variable. I would expect DateTime.Parse () to use the current culture so I usually "dont have to worry about it".

On the other hand, when sending things to a database - I use SQL Server mostly - the DB wants a date in one format. From my installs, thats always in the US format (month/day/year) though that may be an option.

So, youre line of code "strTime = strMonth & "/" & strDay & "/" & strYear" I would not use unless I was passing that date to SQL server as a string. I wouldnt trust a hard-coded format to work with DateTime.Parse() because of the very reasons you mention.

I mention DateTime.Parse but its more or less the same as CDate, but more .NET oriented than the old VB function.

-ner
 
If you already have the values as 3 seperate numbers you could always use the following way to create a date variable and remove the need to handle formatting.
Code:
dim d as New DateTime(2005, 12, 30)

If you know which regional format the date is coded for you could always use the DateTime.Parse method and specify a location

Code:
Dim d as DateTime
d = DateTime.Parse(s, New System.Globalization.CultureInfo("en-US").DateTimeFormat)
 
Ive run into the same problem except with comma decimal separators instead of dates. What I did is write two functions similar to PlausiblyDamps post. One function called Store_Value which converts the entered date into my programs format and another called Display_Value which converts a computed date into the users culture format.
 


Write your reply...
Back
Top