c#中从字符串转换日期时间

本文关键字:日期 时间 转换 字符串 | 更新日期: 2023-09-27 18:11:07

我使用以下代码从String

转换日期
        string JoiningDate="30/11/2013";
        string[] dateconvert = JoiningDate.Split('/');
        string newdate = dateconvert[1] + '/' + dateconvert[0] + '/' + dateconvert[2];
        DateTime JoinDate = Convert.ToDateTime(newdate);

我的系统日期格式是:07/01/14。但是我有以下错误:

 String was not recognized as a valid DateTime.

Then I change我的系统格式是01- july -2014。

现在,如何从字符串转换日期而不考虑系统格式?

c#中从字符串转换日期时间

使用DateTime.ParseExact,指定格式,并指定不变区域性,使其完全不依赖于系统:

DateTime dateTime = DateTime.ParseExact(text, "MM/dd/yyyy",
                                        CultureInfo.InvariantCulture);

(如果您可以自己选择这种格式,我会使用yyyy-MM-dd代替,例如2013-11-30)。这是符合ISO-8601标准的,任何技术人员都很清楚……然而对于世界上很多人来说,07/01/2014看起来就像1月7日…)