I come to you again becase i searched all stack and after found some similar topics anyway no one was working in my case. I ask you to support me in one thing. I have this code:
static class UnixTime {
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
private static readonly long MaxUnixSeconds = (long)((DateTime.MaxValue - UnixEpoch).TotalSeconds);
private const double LongAdj = 1000.0;
public static DateTime ToDateTime(long unixTimeStamp) { return UnixEpoch.AddSeconds(unixTimeStamp / LongAdj); }
public static long FromDateTime(DateTime date) { return (long)((date - UnixEpoch).TotalSeconds * LongAdj); }
public static void Test(long n) {
System.Diagnostics.Debug.WriteLine("UNIX Time = " + n);
var dt = ToDateTime(n);
System.Diagnostics.Debug.WriteLine("DateTime = " + dt);
var fromDt = FromDateTime(dt);
System.Diagnostics.Debug.WriteLine("UNIX Time = " + fromDt);
System.Diagnostics.Debug.WriteLine("IsGood = " + (n==fromDt));
}
public static void Test() { Test(1300123800440); }
}
The output of it is:
UNIX Time = 1300123800440
DateTime = 3/14/2011 5:30:00 PM
UNIX Time = 1300123800440
IsGood = True
its working really fine. Anyway i extracted from above code the one i need to pass datetime as parameter and get Unix timestamp unfortunetly it giving me bad results:
I did like this:
public static long ConvertDateTimeTo(string date)
{
const double LongAdj = 1000.0;
DateTime mydate = Convert.ToDateTime(date);
DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
return (long)((mydate - UnixEpoch).TotalSeconds * LongAdj);
}
use:
Console.WriteLine(ConvertDateTimeTo("14.03.2011 5:30 PM"));
output (should be 1300123800440) but i am receiving:
1300123800000
could you help me out what is wrong here?