I need a conversion from date to millisecond. Every example on stack over flow or the web produces no results for me. Thank you
2 Answers
static readonly DateTime Epoch = new DateTime(1970, 1, 1);
public static double DateTime2Epoch(DateTime dt, bool convertToUTC = true)
{
if (convertToUTC) dt = dt.ToUniversalTime();
return dt.Subtract(Epoch).TotalSeconds;
}
[STAThread]
static void Main(string[] args)
{
DateTime dt = new DateTime(2014, 5, 23, 17, 2, 50);
Console.WriteLine(DateTime2Epoch(dt)); //1400857370 // I'm GMT+2
Console.WriteLine(DateTime2Epoch(dt, false)); //1400864570
}
-
-
1@TristanMcPherson -- The original question had a reference to a specific datetime value (May 23rd 17:02:50) and its equivalent epoch (1400864570): I just wanted to demonstrate this example would produce exactly what icelated was looking for. Of course now that it's been edited, my example just looks like a random value. – May 26 '14 at 08:00
You have to be very careful about using .ToUniversalTime() if any machine running that code has its time zone set to UTC (All Azure servers for example) then that conversion will actually be wrong. You should always check DateTime.Now.Kind and convert only if needed. This goes for all of your time conversions.
If your trying to do anything scientific with the results it should be noted you are not just measuring the time it takes to go from your computer to the server but you are also measuring any clock differences between the machines. If one machine is 60ms off from the other then that is going to be included in your calculation. You could actually be measuring the difference in clock synchronization rather than latency depending on how long the round trip takes.
I suggest converting your local time with DateTime.Now.ToUniversalTime() then convert that into Epoch and compare the UTC values so you know they are in the same time zone. If you run it on daylight savings day for example the results would be vastly different.
Grab the Epoch conversion methods from here: How to convert a Unix timestamp to DateTime and vice versa?
On the server side convert the client back into a DateTime and then subtract one DateTime from the other. This will give you a TimeSpan which you can get TimeSpan.Milliseconds. This will tell you the difference between the two. Note my comments above about machine clocks being out of sync.

- 1
- 1

- 384
- 1
- 4