DateTime issue when trying to convert from string to dateTime

Normally when our system follow UK culture and our server uses US culture then we are facing problem when we are trying to convert String value to Datetime as:

DateTime dt = Convert.ToDateTime(TextBox1.Text);

and if we enter Date in textbox greater than 12 then it shows error as:

String was not recognized as a valid DateTime.

to avoid this we need to change Culture as:

public static DateTime ConvertDate(string s)
    {
        DateTime time;
        try
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
            DateTime time2 = Convert.ToDateTime(s);
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            time = Convert.ToDateTime(time2);
        }
        catch
        {
            throw;
        }
        return time;
    }

for this you need to add two Namespaces

using System.Threading;
using System.Globalization;

To avoid this coding i have created a dll you need to add reference of this in your website and use it easily as:

DateTime dt1 = DateHelper.ConvertDate(TextBox1.Text);

Required Name server:

using DateConversion;

You can download Source code with .dll from below link:

Download

7 Comments

  • Hi,
    Sérgio Amorim
    If you see your given link as
    http://msdn.microsoft.com/en-us/library/kc8s65zs.aspx
    here itself they are telling about culture.
    so same thing i am doing here with different manner...

  • Rajneesh,

    Just like destroying an object or destroying planet earth. It's both about destroying so there is no difference at all. It is the same thing but just in a different manner.

    Cheers,
    Wesley

  • Thanks for the great post.
    Wouldn't it be cool if you have this as an Extension? Then you can call it like:
    DateTime dt1 = TextBox1.Text.Trim().ToDateTime();

    Thanks

  • very useful coding of date time function. Thanks for sharing.

  • You are changing the culture for your whole thread!


  • try
    {
    ...
    }
    catch
    {
    throw;
    }

    What a *great* way to increase your LoC without accomplishing anything!

    I suppose I should be grateful you're not using "catch (Exception ex) { throw ex; }" and destroying the stack-trace, but why bother with this block at all? It doesn't do anything except cluttering up your code.


    DateTime time2 = Convert.ToDateTime(s);
    time = Convert.ToDateTime(time2);

    WTF??! You've already got a DateTime; you don't need to convert it again!


    You don't even need to do any of this; just use the tag in your web.config:

  • Thanks it's working fine

Comments have been disabled for this content.