System.FormatException in mscorlib.dll 用于日期时间转换

System.FormatException in mscorlib.dll for DateTime conversion

我正在尝试将 Active Directory 属性 (whenCreated) 转换为 DateTime,然后是 String,但我一直收到 FormatException,知道为什么吗?这是代码:

string format = "YYYYMMDDHHMMSS.0Z";
DateTime dt = DateTime.ParseExact(sResult.Properties["whenCreated"][0].ToString(),format,CultureInfo.InvariantCulture);
string whenCreated = dt.ToString();

此外,sResult.Properties["whenCreated"][0].ToString() 是 Active Directory 搜索(检索日期)的结果,具有字符串(通用时间)语法。

DateTime.ParseExact 方法需要一个格式字符串,告诉它输入字符串中的哪个部分是有效日期的哪个部分。您的 'd' 格式不符合此标准。我不知道您输入的内容(如果您添加它会有所帮助)。但让我们假设今天是“2017/31/05 10:27:45”。您的格式字符串必须是:"yyyy/dd/MM HH:mm:ss"

DateTime dt = DateTime.ParseExact("2017/31/05 10:27:45","yyyy/dd/MM HH:mm:ss",CultureInfo.InvariantCulture);

根据 OP 链接的 documentation

The format for the Generalized-Time syntax is "YYYYMMDDHHMMSS.0Z". An example of an acceptable value is "20010928060000.0Z"

并且:

If the time is specified in a time zone other than GMT, the differential between the time zone and GMT is appended to the string instead of "Z" in the form "YYYYMMDDHHMMSS.0[+/-]HHMM". An example of an acceptable value is "20010928060000.0+0200"

因此您需要两个格式字符串才能解析字符串,如下所示:

string adDate = "20010928060000.0Z";
string adDate2 = "20010928060000.0+0200";

string format = "yyyyMMddhhmmss.0Z";
string format2 = "yyyyMMddhhmmss.0zzz";
DateTime dtdtdt = DateTime.ParseExact(adDate2, new string[] { format, format2 }, 
                           CultureInfo.InvariantCulture,DateTimeStyles.None);