Date.Parse question

Joined
Mar 26, 2009
Messages
15
Programming Experience
Beginner
Hi,

When reading a date from a file which is in the format yyyy/MM/dd HH:mm:ss, how can I ensure that the date gets parsed correctly regardless of the country or culture where my program is installed. I'm guessing that the following is not enough

VB.NET:
Dim s as String = "2010/05/06 16:22:00" ' i.e. May 6th 2010 4:22PM
Dim d as Date = Date.Parse(s)

i.e. it could get interpretted (?) as either

May 6th 2010 4:22PM (Correctly)
June 5th 2010 4:22PM (Incorrectly)

Thanks
 
Hi MattP,

Thanks for the reply. I looked at that method and read the help about it before posting my query. I guess what I was trying to say in my original post is that I'm a bit unclear on how to implement it. Could you provide an example?

The reference material states that The IFormatProvider parameter supplies culture-specific formatting information about the string containing a date and time to convert however I'm not sure which culture to use - I want things to be culture independent. Anyway I found another method ParseExact which may work.

VB.NET:
Dim s as String = "2010/05/06 16:22:00" ' i.e. May 6th 2010 4:22PM
DateTime.ParseExact(s, "yyyy/MM/dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture)

The only thing is that it's a bit inflexible (i.e. it will fail if the string is another format e.g. 2010/5/6 16:22:00 - note the leading zeroes are missing). The more general Parse method as you suggested may be more flexible?

Thanks
 
VB.NET:
        Dim sDate1 As String = "2010/05/06 16:22:00"
        Dim expectedDateFormats As String() = {"yyyy/MM/dd HH:mm:ss", "yyyy/M/d HH:mm:ss"}
        Dim dt1 As DateTime = DateTime.ParseExact(sDate1, _
                                                  expectedDateFormats, _
                                                  System.Globalization.CultureInfo.InvariantCulture, _
                                                  Globalization.DateTimeStyles.AllowWhiteSpaces)

        Dim sDate2 As String = "2010/5/6 16:22:00"
        Dim dt2 As DateTime = DateTime.ParseExact(sDate2, _
                                                  expectedDateFormats, _
                                                  System.Globalization.CultureInfo.InvariantCulture, _
                                                  Globalization.DateTimeStyles.AllowWhiteSpaces)
 
Back
Top