Convert LDAP AccountExpires to DateTime in C# - c#

I want to convert 18 digit string from LDAP AccountExpires to Normal Date Time Format.
129508380000000000 >> May 26 2011
I got the above conversion from using the following link.
http://www.chrisnowell.com/information_security_tools/date_converter/Windows_active_directory_date_converter.asp?pwdLastSet,%20accountExpires,%20lastLogonTimestamp,%20lastLogon,%20and%20badPasswordTime
I tried to convert by using DateTime.Parse or Convert.ToDateTime. But no success.
Anyone know how to convert it? Thanks very much.

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

If you View Source on the link you posted you should see a Javascript conversion algorithm that should translate quite nicely to c#

For Ruby
def ldapTimeConverter(ldap_time)
Time.at((ldap_time/10000000)-11644473600)
end

I stumbled across this working on a PowerShell script. I found I can query the accountexpirationdate property and no conversion is required.

Someone had the "best" way above but when it's set to never expired, the value is zero.
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);
}

I'll provide a perfect answer to this question using which you will be able to convert and DateTime to active directory long int format and will be also able to do the vice versa of it.
Here is a solution to it:-
To get DateTime from AD
string tickstring = de.Properties["accountExpires"][0].ToString();
long Ticks = (long) tickstring;
DateTime ReferenceDate = new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc);
long ExpireDateTicks = Ticks + ReferenceDate.Ticks;
DateTime ExpireDate = new DateTime(ExpireDateTicks);
To convert DateTime to AD long integer format
DateTime ReferenceDate = new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime ExpireDate = new DateTime(Request.EndDate.Year, Request.EndDate.Month, Request.EndDate.Day, 0, 0, 0);
long Ticks = ExpireDate.Ticks - ReferenceDate.Ticks;
NewUser.accountExpires = Ticks.ToString();

Related

How can i translate string timestamp to Date?

I has in string format, timestamp 1593339378252, i need convert this, to a normal human date-20.06.2020
I try this code
var timestamp = Convert.ToInt64(dateFrom);
// Format our new DateTime object to start at the UNIX Epoch
System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
// Add the timestamp (number of seconds since the Epoch) to be converted
dateTime = dateTime.AddSeconds(timestamp);
but if i try convert to int32,16,64 i get System.ArgumentOutOfRangeException
It seems that your timestamp actually contains number of milliseconds, not seconds:
new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc).AddMilliseconds(1593339378252)
// on my machine - 28-Jun-20 10:16:18 AM
You can use var dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(yourValue);
For more information, also look at the documentation

What are valid UTCDateTime type string formats for AIF transfomrmations?

Im am trying to write a .net class that transforms a piece of xml to a AX UtcDateTime type.
The class is used in an inbound transformation.
Original xml:
<DateTime>
<Date>2014-06-12</Date>
<Time>10:52:00</Time>
<Zone>+02:00</Zone>
</DateTime>
My resulting xml leads to an exeption in the exeptionlog:
"The value '2014-06-12T12:52:00+02:00' is not a valid UtcDateTime type."
I think AIF expect the Z at the end of the value, and I am not sure if the localDateTime is mandatory and or if the milliseconds are a requirement.
I would like to know how the UtcDateTime field in transformed xml should be formatted to be accepted by AIF.
Like so:
<MessageHeaderDateTime localDateTime="2014-06-12T10:52:00+02:00">2014-06-12T08:52:00Z</MessageHeaderDateTime>
or like so:
<MessageHeaderDateTime localDateTime="2014-06-12T10:52:00.1108723+02:00">2014-06-12T08:52:00.1108723Z</MessageHeaderDateTime>
or are other things missing?
My Code
DateTime netdttm = new DateTime(year, month, day, hour, minute, second, DateTimeKind.Utc);
TimeSpan timespan = new TimeSpan(zhour, zminute, 0);
DateTime netdttmoffset = netdttm.Subtract(timespan);
datetime.Value = netdttmoffset;
datetime.localDateTime = netdttmoffset.ToLocalTime();
datetime.localDateTimeSpecified = true;
I use a similar appraoch for the case where I use utcnow.
Problem i that I have limited testing possibilities due to hot-swapping being disbled in the environment where I have to develop my code. So I would like to be certainin about the formatting.
Thanx for your help.
I finally got it to work. My solution:
//declare the AX utcdatetime type from the cs class generate with:
//xsd C:\...\SharedTypes.xsd C:\..\AIFschema.xsd /Classes /Out:C:\location\of\csfile\
AxType_DateTime datetime = new AxType_DateTime();
//Ax store the time in GMT with an optional local time. My XML can have any timezone.
datetime.timezone = AxdEnum_Timezone.GMT_COORDINATEDUNIVERSALTIME;
//I set this to false as i am not interested in actually storing the local time. Plus AX fails over the formatting .net returns.
datetime.timezoneSpecified = false;
//{... left out code to retrieve the hours, minutes etc from my XML}
//declare the .net datetime variable with the values from the xml:
DateTime netdttm = new DateTime(year, month, day, hour, minute, second, millisecond, DateTimeKind.Utc);
DateTime netdttmoffset = new DateTime();
// (optional field) <zone>+01:00</zone>
if (message.Header.DateTime.Zone != null)
{
{... left out code to retrive zone offset info from xml}
TimeSpan timespan = new TimeSpan(zhour, zminute, 0);
netdttmoffset = netdttm.Subtract(timespan);
}
else //no zone, so datetime == GMT datetime.
{
netdttmoffset = netdttm;
}
datetime.Value = netdttmoffset;
datetime.localDateTime = netdttmoffset.ToLocalTime();
//do not output to xml, or AX will fail over this.
datetime.localDateTimeSpecified = false;
Result xml snippet as accepted by AX:
<MessageHeaderDateTime>2014-07-30T16:41:10.001Z</MessageHeaderDateTime>
I found this to be easier. If you want a particular datetime, say Jan 31, 2015 8:00 am, to be stored in AX, the .net code to make it happen would be
DateTime utcDateTime = new DateTime(2015, 1, 31, 8, 0, 0).ToUniversalTime();
var workerStartDate = new AxdExtType_HcmEmploymentStartDateTime
{
Value = utcDateTime
};
The XML generated would be would be <WorkerStartDate>2015-05-12T13:00:00Z</WorkerStartDate>, assuming you are 5 hours behind GMT on the computer that runs the .net code. The AX database will store the value 2015-05-12T13:00:00Z as well.
<dyn:StartDate>2014-06-22T00:00:00.000+02:00</dyn:StartDate>
This format always does the trick for me. (Notice the ms)

Javascript epoch in c#

I search the forum for my problem but found nothing. :(
This DateTime conversion drives me mad.
I try to convert a millisecond epoch to DateTime.
I found this Methode in the Internet:
private DateTime TimeFromUnixTimestamp(int unixTimestamp)
{
DateTime unixYear0 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
long unixTimeStampInTicks = unixTimestamp * TimeSpan.TicksPerSecond;
DateTime dtUnix = new DateTime(unixYear0.Ticks + unixTimeStampInTicks);
return dtUnix;
}
private DateTime TimeFromJavaTimestamp(long javaTimestamp)
{
return TimeFromUnixTimestamp((int)(javaTimestamp / 1000));
}
Now to test the method I run this code in JavaScript:
Date.UTC(2014,05,06,0,0,0,0);
You can test it here (jsfiddler)
The result is 1402012800000.
So far so good. Now I test my c# methode:
var test = TimeFromJavaTimestamp(1402012800000L);
and as result I get {06.06.2014 00:00:00}!
One month offset to what I do expected??
Can somebody explain this to me???
Regards Steffen
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC
month An integer between 0 and 11 representing the month.
So, yeah, the month 05 is June. Looks like your code is working.
This is how I would do it.
In JavaScript:
var timestamp = new Date().getTime();
Then in C# to convert a JavaScript timestamp to a DateTime object:
public static DateTime ToDateTime(long timestamp)
{
var dateTime = new DateTime(1970,1,1,0,0,0,0, DateTimeKind.Utc);
return dateTime.AddSeconds(timestamp / 1000).ToLocalTime();
}

Converting ticks to DateTime

There are a number of questions on this site explaining how to do this. My problem I when I do what seems to work for everyone else I don't get the correct date or time. The code is ...
long numberOfTicks = Convert.ToInt64(callAttribute);
startDateTime = new DateTime(numberOfTicks);
The value of callAttribute is = "1379953111"
After converting it the value of numberOfTicks = 1379953111
But the DateTime ends up being startDateTime = {1/1/0001 12:02:17 AM}
I have taken the same value for ticks and converted it online and it comes up with the correct date/time.
What am I doing wrong?
Your value doesn't seem to be a number of ticks; I suspect it's a UNIX timestamp (number of seconds since 1970/01/01 UTC)
Here's a function to convert from a UNIX timestamp:
static readonly DateTime _unixEpoch =
new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static DateTime DateFromTimestamp(long timestamp)
{
return _unixEpoch.AddSeconds(timestamp);
}

DateTime's representation in milliseconds?

I have a SQL-server timestamp that I need to convert into a representation of time in milliseconds since 1970. Can I do this with plain SQL? If not, I've extracted it into a DateTime variable in C#. Is it possible to get a millisec representation of this ?
Thanks,
Teja.
You're probably trying to convert to a UNIX-like timestamp, which are in UTC:
yourDateTime.ToUniversalTime().Subtract(
new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
).TotalMilliseconds
This also avoids summertime issues, since UTC doesn't have those.
In C#, you can write
(long)(date - new DateTime(1970, 1, 1)).TotalMilliseconds
As of .NET 4.6, you can use a DateTimeOffset object to get the unix milliseconds. It has a constructor which takes a DateTime object, so you can just pass in your object as demonstrated below.
DateTime yourDateTime;
long yourDateTimeMilliseconds = new DateTimeOffset(yourDateTime).ToUnixTimeMilliseconds();
As noted in other answers, make sure yourDateTime has the correct Kind specified, or use .ToUniversalTime() to convert it to UTC time first.
Here you can learn more about DateTimeOffset.
There are ToUnixTime() and ToUnixTimeMs() methods in DateTimeExtensions class
DateTime.UtcNow.ToUnixTimeMs()
SELECT CAST(DATEDIFF(S, '1970-01-01', SYSDATETIME()) AS BIGINT) * 1000
This does not give you full precision, but DATEDIFF(MS... causes overflow. If seconds are good enough, this should do it.
This other solution for covert datetime to unixtimestampmillis C#.
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long GetCurrentUnixTimestampMillis()
{
DateTime localDateTime, univDateTime;
localDateTime = DateTime.Now;
univDateTime = localDateTime.ToUniversalTime();
return (long)(univDateTime - UnixEpoch).TotalMilliseconds;
}
Using the answer of Andoma, this is what I'm doing
You can create a Struct or a Class like this one
struct Date
{
public static double GetTime(DateTime dateTime)
{
return dateTime.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
}
public static DateTime DateTimeParse(double milliseconds)
{
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(milliseconds).ToLocalTime();
}
}
And you can use this in your code as following
DateTime dateTime = DateTime.Now;
double total = Date.GetTime(dateTime);
dateTime = Date.DateTimeParse(total);
I hope this help you

Categories

Resources