Storing current time as integer
I would like to store the current time as an integer, re perl. I know I need a TimeSpan, starting from windo开发者_运维知识库ws time start. I know windows time starts from when?, Jan 1st, 1601.
scope_creep
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);
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.
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
精彩评论