Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

c# - Parsing DateTime on Localized Systems

We have a web application that produces reports. Data are taken from a database.

When we ran the web application on a localized system, it blows up. We traced the problem on a DateTime.Parse(dateString); call.

The dates stored in the database is somewhat dependent on the locale of the machine.

On an English system, the date is stored as MM/DD/YYYY (06/25/2009) which is perfectly normal.

On a Russian system, the date is stored as MM.DD.YYYY (06.25.2009). This is weird because the default setting (I checked) for Short Date format in Russian Systems is dd.MM.yyyyy... So it should be 25.06.2009. I don't it get why it accepted the default separator (.) but not the default date format.

So anyway, how can I parse the date string on a localized system? If I use the Russian cultureinfo, it would still throw an error since it is expecting dd.MM.yyyyy.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should never store a localized date string in the database.

You must store dates in date columns and then localize the data at the moment of showing it.

1. Set the locale of your site UI

This example set the lang according to the request path, but may have other mechanism.

Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
    Dim lang As String
    If HttpContext.Current.Request.Path.Contains("/en/") Then
        lang = "en" 'english'
    ElseIf HttpContext.Current.Request.Path.Contains("/pt/") Then
        lang = "pt" 'portugues'
    Else
        lang = "es" 'espa?ol, the default for the site'
    End If
    Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang)
    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang)

End Sub

2. Get the input to date variables

Getting the data from the text input is easy, this is an example, but with a date validator you should be ok.

dim theDate as date
if IsDate( txtDate.text ) then
   theDate = DateTime.Parse(txtDate.text)
else
   'throw exception or something
end if

Edit

Since you say you can't change the way it is stored, you are in big trouble, unless you have in the db record some way to tell the format of the date. The problem is not the separators, but when you find a date like 6/3/2009 you dont know if it is 6 of march or 3 of june.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...