Javascript epoch in c# - 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();
}

Related

Convert a time in milliseconds to local date string

I am trying to convert a TimeStamp in milliseconds to a local date time. But this is weird.
The date is increased by 1 day. I don't know how stupid may I sound, but I would really be happy to have someone throw light on this.
CODE:
public static DateTime ConvertToLocalDate(string timeInMilliseconds){
double timeInTicks = double.Parse(timeInMilliseconds);
TimeSpan dateTimeSpan = TimeSpan.FromMilliseconds(timeInTicks);
DateTime dateAfterEpoch = new DateTime(1970, 1, 1) + dateTimeSpan;
DateTime dateInLocalTimeFormat = dateAfterEpoch.ToLocalTime();
return dateInLocalTimeFormat;
}
For example, if I pass:
1579631400000 which is equivalent to: 2020-01-21T18:30:00
it returns: 1/22/2020 12:00:00 AM
What is wrong?
Since your ConvertToLocalDate function returns the date and time to your local time zone. You need to convert it to UTC to get the expected date and time.
class Program
{
static void Main(string[] args)
{
Console.WriteLine(ConvertToLocalDate("1579631400000").ToUniversalTime());
Console.ReadKey();
}
public static DateTime ConvertToLocalDate(string timeInMilliseconds)
{
double timeInTicks = double.Parse(timeInMilliseconds);
TimeSpan dateTimeSpan = TimeSpan.FromMilliseconds(timeInTicks);
DateTime dateAfterEpoch = new DateTime(1970, 1, 1) + dateTimeSpan;
DateTime dateInLocalTimeFormat = dateAfterEpoch.ToLocalTime();
return dateInLocalTimeFormat;
}
}
Or simply do not use ToLocalTime() inside your ConvertToLocalDate (if this is the case your function should not be named as ConvertToLocalDate)
Do nor use ToLocalTime().rest will work fine

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

.NET DateTime to time_t in seconds

There is C code :
time1=((double)dt1-25569.0)*86400.0;
it's convert from TDateTime (VCL) to time_t format in seconds, so finally I need to get time_t format from .NET DateTime
about time_t :
It is almost universally expected to be an integral value representing
the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC. This
is due to historical reasons, since it corresponds to a unix
timestamp, but is widely implemented in C libraries across all
platforms.
So to get seconds in .NET I'm doing this (F#):
let seconds(dt : DateTime) =
(dt.Ticks/10000000L)
or on C# (to use more popular C# tag) :
Int64 seonds(DateTime dt)
{ return (dt.Ticks/ ((Int64)10000000)); }
// hope it works, but please correct if I mistaken
As far as I understand it's time from 12:00:00 Jan 1, 0001 UTC.
So to use time_t format I need to add 1970 years in seconds.
So final function must be (F#):
let seconds(dt : DateTime) =
(dt.Ticks/10000000L) + 31536000*1970
C# :
Int64 seonds(DateTime dt)
{ return (dt.Ticks/ ((Int64)10000000)) + 31536000*1970; }
I really afraid I made mistake here. Please examine this solution ! (check if this is done right)
Thank you
try
(dt - new DateTime (1970, 1, 1)).TotalSeconds
see
http://msdn.microsoft.com/en-us/library/system.timespan.totalseconds.aspx
http://msdn.microsoft.com/en-us/library/xcfzdy4x.aspx
this seems a little tidier? You could make the epoch a static datetime if you will be using it a lot.
DateTime date = DateTime.Now;
DateTime epoch = new DateTime(1970, 1, 1);
TimeSpan span = (date - epoch);
double unixTime = span.TotalSeconds;
I suggest the following code. It seems to better transport the meaning of the code
private static readonly DateTime REFERENCE = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
Int64 seconds(DateTime dt)
{
return (dt - REFERENCE).TotalSeconds;
}
In C#:
Int64 Secs(DateTime dt)
{
var delta = dt - new DateTime(1970, 1, 1);
return Convert.ToInt64(delta.TotalSeconds);
}
After reading #jheriko's comment on the accepted answer I wrote a quick console app to test whether time() from msvcrt.dll produced differing results to calculations using the managed date/time functions, which fortunately they do not, provided UTC is used. Generally speaking, wherever possible, dates and times should be calculated with and stored in UTC as a common base, and then converted back to the relevant timezone for display if necessary.
For reference, and to illustrate different ways of arriving at the number of seconds between 1st Jan 1970 and now, my test code was:
class Program
{
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
public unsafe static extern int time(int* timer);
static unsafe void Main(string[] args)
{
DateTime now = DateTime.Now;
DateTime utc_now = DateTime.UtcNow;
int time_t_msvcrt = time(null);
int time_t_managed = (int)Math.Floor((now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds);
int time_t_managed_2 = (int)Math.Floor((utc_now - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds);
Console.WriteLine(time_t_msvcrt == time_t_managed);
Console.WriteLine(time_t_msvcrt == time_t_managed_2);
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime time_t_now = epoch.Add(TimeSpan.FromSeconds(time_t_msvcrt));
long now_secs = now.Ticks / 10000000L;
long utc_now_secs = utc_now.Ticks / 10000000L;
long time_t_now_secs = time_t_now.Ticks / 10000000L;
Console.WriteLine(time_t_now_secs == now_secs);
Console.WriteLine(time_t_now_secs == utc_now_secs);
Console.ReadLine();
}
}
This produces the output
True
True
True
True
as expected.

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