Convert LDAP AccountExpires to DateTime in C#

Edited answer

It's the number of ticks since Jan-01-1601 in UTC, according to Reference, which describes the significance of the year 1601. Good background reading.

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

Original Accepted Answer

It's the number of ticks since Jan-02-1601.

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

You can use the FromFileTime method on the DateTime class, but watch out, when this field is set to not expire, it comes back as the Int64.MaxValue and doesn't work with either of these methods.

Int64 accountExpires = 129508380000000000;

DateTime expireDate = DateTime.MaxValue;

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

Some info for anyone who came here looking to set the AccountExpires value.

To clear the expiry is nice and easy:

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

However if you try to directly write back an int64 / long:

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

You can get a 'COMException was unhandled - Unspecified error'

Instead write back the value as a string data type:

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

Be aware of the time of day you are setting, for consistancy with ADUC the time should be 00:00.

Instead of .Now or .UtcNow you can use .Today:

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

Other input like dateTimePicker you can replace the time, Kind as Local for the Domain Controller:

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();

Tags:

C#

Datetime

Ldap