开发者

DateTime.TryParse string in wrong format

in C# I'm trying to do a DateTime.TryParse on a string field which I am getting from a DataFeed which I know is in "MM/dd/YYYY" format. e.g.

DateTime dt = DateTime.TryParse("01/30/11");

Only thing is now "dt" is in the incorrect format to be stored into my Database which has a DateTime locale setting of "dd/MM/YYYY".

How do I go about parsing the string field correctly into dt and then into my DB? What would be the best way to handle this? If I set the globalization of my CurrentThread to en-US, then dt would be in en-US format, however when inserting into the DB, it is still incorrectly st开发者_运维技巧ored? :S

Thanks

David


Use the DateTime.ParseExact method:

DateTime dt = DateTime.ParseExact("15/12/2011", "dd/MM/yyyy", CultureInfo.InvariantCulture);

If you want to convert the DateTime value to a string back, use the following code:

string dtString = string.Format("{0: dd/MM/yyyy}", dt);


Try using TryParseExact.

http://msdn.microsoft.com/en-us/library/system.datetime.tryparseexact.aspx


I hope you understand, the TryParse be made by the if statement, see the following example,

  private void button1_Click_1(object sender, EventArgs e)
    {

        DateTime myData = new DateTime();

        if (DateTime.TryParse(this.textBox1.Text,out myData))
        {
            // your filed db = myData
        }
    }

you then enter in the block if the update of the database field, according to the cultures set on your PC.

Bye

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜