在C#中将LDAP AccountExpires转换为DateTime

TTC*_*TCG 15 c# datetime ldap

我想将来自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进行转换.但没有成功.

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

Wal*_*alk 20

您可以使用DateTime类的FromFileTime方法,但是要注意,当此字段设置为未到期,它回来为Int64.MaxValue,不与这些方法之一工作.

Int64 accountExpires = 129508380000000000;

DateTime expireDate = DateTime.MaxValue;

if (!accountExpires.Equals(Int64.MaxValue))
    expireDate = DateTime.FromFileTime(accountExpires);
Run Code Online (Sandbox Code Playgroud)


age*_*t-j 18

编辑回答

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

var accountExpires = 129508380000000000;
var dt = new DateTime(1601, 01, 01, 0, 0, 0, DateTimeKind.Utc).AddTicks(accountExpires);
Run Code Online (Sandbox Code Playgroud)

原始接受的答案

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

DateTime dt = new DateTime(1601, 01, 02).AddTicks(129508380000000000);
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一下,它似乎是 UTC 时间,但您需要确定一下。 (2认同)
  • 它实际上是自1601-01-01以来的刻度数,而不是1601-01-02. (2认同)

Who*_*ich 9

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

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

entry.Properties["accountExpires"].Value = 0;
Run Code Online (Sandbox Code Playgroud)

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

entry.Properties["accountExpires"].Value = dt.ToFileTime();
Run Code Online (Sandbox Code Playgroud)

你可以得到'COMException未处理 - 未指定的错误'

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

entry.Properties["accountExpires"].Value = dt.ToFileTime().ToString();
Run Code Online (Sandbox Code Playgroud)

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

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

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

像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();
Run Code Online (Sandbox Code Playgroud)