Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.Ticks in .NET - how and why is it used?

Tags:

.net

I have been using C# for quite some time, and have suddenly come across DateTime.Now.Ticks.

What is it for?

like image 474
S. Vikneshwar Avatar asked Mar 10 '12 07:03

S. Vikneshwar


1 Answers

It represents the total number of ticks in local time (not UTC) since the DateTime epoch, which is midnight on January 1st in the year 1AD. (Each tick is 100 nanoseconds; there are 10,000 ticks in a millisecond.)

To break it down, DateTime.Now is a static property returning a DateTime representing the current time.

Then DateTime.Ticks is an instance property on DateTime, returning the number of ticks since midnight on January 1st, 1AD. It gets more complicated due to time zones (and DateTime's poor design) but that's the basics.

A tick is the smallest unit of time used in DateTime and TimeSpan. You typically use it to make sure you can completely round-trip a value without losing any information.

Note that it's not the same thing as the ticks returned by Stopwatch.ElapsedTicks, which are system-dependent; their length can be determined using StopWatch.Frequency.

like image 186
Jon Skeet Avatar answered Nov 07 '22 08:11

Jon Skeet