How can i translate string timestamp to Date? - c#

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

Related

c#: Get timezone offset stored in date object

I am getting a date from API response as:
string jsonResponse = #"{'endDate': '/Date(-62135578800000-0500)/'}";
Now when I deserialize the reponse using NewtonSoft.json I get the result as:
MyClass obj = JsonConvert.DeserializeObject<MyClass>(jsonResponse);
Console.WriteLine(obj.endDate); // 1/1/0001 5:00:00 AM
Now again after some operation I have to post the data to the server in that same format of the date I have received:
DateTime endDateValue = new DateTime();
endDateValue = obj.endDate
MyClass objNew = new MyClass{
endDate = endDateValue
};
string jsonPostData = JsonConvert.SerializeObject(objNew);
string response = JsonConvert.SerializeObject(jsonPostData);
Console.WriteLine(response);//{"endDate":"0001-01-01T05:00:00+00:00"}
Since I don't want this format "0001-01-01T05:00:00+00:00". It should be same as '/Date(-62135578800000-0500)/'.
Till now I followed this link to understand the type of format:
PHP date format /Date(1365004652303-0500)/
I am able to get the timestamp like this:
DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
long unixTimeStampInTicks = (endDateValue.ToUniversalTime() - unixStart).Ticks;
Console.WriteLine(unixTimeStampInTicks/10000);//-62135578800000
Is there any method in c# to get the offset value -0500 present in this date object like in javascript getTimezoneOffset() method returns the offset.
Simply use DateTimeOffset, not DateTime - it's a similar structure, only with an explicit Offset property. Plain DateTime doesn't have a concept of time zones.
This means using it within MyClass, and deserializing to it.

How to get correct timestamp in C#

I would like to get valid timestamp in my application so I wrote:
public static String GetTimestamp(DateTime value)
{
return value.ToString("yyyyMMddHHmmssffff");
}
// ...later on in the code
String timeStamp = GetTimestamp(new DateTime());
Console.WriteLine(timeStamp);
output:
000101010000000000
I wanted something like:
20140112180244
What have I done wrong?
Your mistake is using new DateTime(), which returns January 1, 0001 at 00:00:00.000 instead of current date and time. The correct syntax to get current date and time is DateTime.Now, so change this:
String timeStamp = GetTimestamp(new DateTime());
to this:
String timeStamp = GetTimestamp(DateTime.Now);
var Timestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
var timestamp = DateTime.Now.ToFileTime();
//output: 132260149842749745
This is an alternative way to individuate distinct transactions. It's not unix time, but windows filetime.
From the docs:
A Windows file time is a 64-bit value that represents the number of 100-
nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601
A.D. (C.E.) Coordinated Universal Time (UTC).
For UTC:
string unixTimestamp = Convert.ToString((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
For local system:
string unixTimestamp = Convert.ToString((int)DateTime.Now.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
Int32 unixTimestamp = (Int32)(TIME.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
"TIME" is the DateTime object that you would like to get the unix timestamp for.
internal static string UnixToDate(int Timestamp, string ConvertFormat)
{
DateTime ConvertedUnixTime = DateTimeOffset.FromUnixTimeSeconds(Timestamp).DateTime;
return ConvertedUnixTime.ToString(ConvertFormat);
}
int Timestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
Usage:
UnixToDate(1607013172, "HH:mm:ss"); // Output 16:32:52
Timestamp; // Output 1607013172

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

Convert LDAP AccountExpires to DateTime in 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();

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