views:

107

answers:

3

Hi, I would like to store the current time as an integer, re perl. I know I need a TimeSpan, starting from windows time start. I know windows time starts from when?, Jan 1st, 1601.

scope_creep

+4  A: 

Does it HAVE to be an integer? Could it be a long? If so, the easy answer is to use the .Ticks property on a DateTime object.

You can also get the "minimum" DateTime supported from the MinValue property. You could then use the normal subtraction operator to get a TimeSpan difference between two DateTimes.

Also, storing times as integers can be tricky, because the maximum (unsigned) int value can only store about 136 years. If you need resolution beyond that, you need to use long, or at least make sure you pick your starting date appropriately.

UPDATE: To address your comments, you could store the time and then calculate seconds like such:

long Ticks1 = DateTime.Now.AddSeconds(-10).Ticks;
long Ticks2 = DateTime.Now.Ticks;
TimeSpan elapsedTime = TimeSpan.FromTicks(Ticks2 - Ticks1);
Michael Bray
Hi MichaelIt should be a long to ensure accuracy. It just needs to resolve to seconds or microseconds, so I can do substraction on them. The reason I need them, is to measure recorded values don't pass a threshold value within a window value, i.e. for example, 3 measured values within a 20 second window, the window is moved forward.
scope_creep
In that case, you should definitely use the .Ticks - its built in and you can easily reconstruct a DateTime from a given value of Ticks. 1 second will equate to 10,000,000 ticks, so plenty of resolution. I've updated the reesponse to provide an example.
Michael Bray
A: 

The DateTime value type represents dates and times with values ranging from 12:00:00 midnight, January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.)

http://msdn.microsoft.com/en-us/library/system.datetime.aspx

bugtussle
FileTime is based on the 1601http://blogs.msdn.com/mikekelly/archive/2009/01/17/unix-time-and-windows-time.aspx
bugtussle
+1  A: 

You can store the time as an integer starting from any point you like. Just make sure its always the same. To convert from your value to a DateTime object create a new DateTime object with the start date you chose and add the amount of seconds stored in your integer variable to get back to a usable object. To convert from a DateTime to your value, simply use the DateTime.Subtract method with a DateTime object instantiated to the start date.

Guy