在C#中将LDAP AccountExpires转换为DateTime

我想将来自LDAP AccountExpires的18位数字符串转换为正常日期时间格式。

129508380000000000 >> 2011年5月26日

我使用以下链接获得了上述转换。

http://www.chrisnowell.com/information_security_tools/date_converter/Windows_active_directory_date_converter.asp?pwdLastSet,%20accountExpires,%20lastLogonTimestamp,%20lastLogon,%20and%20badPasswordTime

我尝试使用DateTime.Parse或Convert.ToDateTime进行转换。 但没有成功。

有谁知道如何转换它? 非常感谢。

编辑回答

根据参考文献 ,它是UTC自01年1月1日至1月1日以来的滴答数,它描述了1601年的重要性。良好的背景阅读。

var accountExpires = 129508380000000000; var dt = new DateTime(1601, 01, 01, 0, 0, 0, DateTimeKind.Utc).AddTicks(accountExpires); 

原始接受的答案

这是自2001年1月2日至1月1日以来的滴答数。

 DateTime dt = new DateTime(1601, 01, 02).AddTicks(129508380000000000); 

您可以在DateTime类上使用FromFileTime方法,但请注意,当此字段设置为未过期时,它将作为Int64.MaxValue返回,并且不适用于这两种方法。

 Int64 accountExpires = 129508380000000000; DateTime expireDate = DateTime.MaxValue; if (!accountExpires.Equals(Int64.MaxValue)) expireDate = DateTime.FromFileTime(accountExpires); 

来自这里寻找设置AccountExpires值的任何人的一些信息。

要清除过期是好的和简单的:

 entry.Properties["accountExpires"].Value = 0; 

但是,如果您尝试直接写回int64 / long:

 entry.Properties["accountExpires"].Value = dt.ToFileTime(); 

你可以得到’COMException未处理 – 未指定的错误’

而是将值写回字符串数据类型:

 entry.Properties["accountExpires"].Value = dt.ToFileTime().ToString(); 

请注意您设置的时间,与ADUC的一致性时间应为00:00。

而不是.Now或.UtcNow你可以使用。今天:

 var dt1 = DateTime.Today.AddDays(90); entry.Properties["accountExpires"].Value = dt1.ToFileTime().ToString(); 

其他输入如dateTimePicker可以替换域控制器的时间,Kind as Local:

 var dt1 = dateTimePicker1.Value; var dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, 0, 0, 0, DateTimeKind.Local); entry.Properties["accountExpires"].Value = dt2.ToFileTime().ToString(); 

如果您在发布的链接上查看源代码,您应该看到一个Javascript转换算法,它应该很好地转换为c#

我偶然发现了PowerShell脚本。 我发现我可以查询accountexpirationdate属性,不需要转换。

有人在上面有“最好的”方式但是当它设置为永不过期时,值为零。

 public static DateTime GetAccountExpiresDate(DirectoryEntry de) { long expires = de.properties["accountExpires"].Value; if (expires == 0) // doesn't expire return DateTime.MaxValue; return DateTime.FromFileTime(expires); }