c# and Date Culture Problems
Asked Answered
B

4

4

I've written a asp.net app and one of my postback routines simply saves user submitted form data to a sql 2005 db. All runs great on my development machine but when I deploy to the live site I'm getting invalid dates from my parse date checker.

Basically it is expecting an american date format on the live machine but this is not what I want. The user needs to be able to enter in dd/MM/yyyy format. So a valid date like 21/10/2009 returns errors on live server but not on my dev machine. Below is the code that throws the exception.

DateTime dt;
dt = DateTime.Parse(sdate);  
//sdate in GB dd/MM/yyyy format

Is it possible to force the parse routine to expect the date in dd/MM/yyyy format?

Building answered 5/3, 2009 at 9:56 Comment(0)
A
9

Do like this:

    System.Globalization.CultureInfo cultureinfo = 
        new System.Globalization.CultureInfo("en-gb");
    DateTime dt = DateTime.Parse("13/12/2009", cultureinfo);
Acerbity answered 5/3, 2009 at 10:23 Comment(1)
What about it you put "12/12/9999" in theory that's a valid date but from a human standpoint it's not valid so therefore the code you have placed there will never fail for a date where the year is 2012 currently ..we've never reached DateTime.MaxValue of 9999Limewater
L
6

You can use DateTime.ParseExact to specify an expected format.

Leatriceleave answered 5/3, 2009 at 9:59 Comment(0)
C
4

Another option is to specify the culture you wish to use in the web.config file:

<system.web>
    ...
    <globalization 
        culture="da-DK" 
        uiCulture="da-DK" requestEncoding="utf-8" responseEncoding="utf-8"
    />
</system.web>
Clearcole answered 5/3, 2009 at 10:16 Comment(0)
R
2

Yes, ParseExact will do that as mentioned by Matt.

The code would be something like:

dt  = DateTime.ParseExact(sdate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Reflection answered 5/3, 2009 at 15:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.