简体   繁体   English

DateTime.TryParse 字符串格式错误

[英]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.在 C# 中,我试图对从 DataFeed 获取的字符串字段执行 DateTime.TryParse,我知道该字段是“MM/dd/YYYY”格式。 eg例如

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".现在唯一的问题是“dt”的格式不正确,无法存储到我的数据库中,该数据库的 DateTime 语言环境设置为“dd/MM/YYYY”。

How do I go about parsing the string field correctly into dt and then into my DB?如何将字符串字段正确解析为 dt 然后解析为我的数据库? 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 stored?如果我将 CurrentThread 的全球化设置为 en-US,那么 dt 将采用 en-US 格式,但是当插入数据库时,它仍然存储不正确? :S :S

Thanks谢谢

David大卫

Use the DateTime.ParseExact method:使用DateTime.ParseExact方法:

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:如果要将 DateTime 值转换回字符串,请使用以下代码:

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

I hope you understand, the TryParse be made by the if statement, see the following example,我希望你明白,TryParse 是由 if 语句组成的,看下面的例子,

  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.然后,根据 PC 上设置的文化,如果数据库字段更新,则在块中输入。

Bye再见

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM