I have a time tick (635655080937662522) I created with C# and stored in a database column. How can I verify that this value is a tick and not something else? Does a tick have a certain format?
As others have said, a tick is just a number, but there are some important differences, depending on where the tick came from.
Ticks from a DateTime or DateTimeOffset are 100ns each, and range from DateTime.MinValue.Ticks to DateTime.MaxValue.Ticks, which is 0 to 3155378975999999999. Note that this is much smaller than Int64.MaxValue.
Ticks from a TimeSpan are also 100ns each, but range from TimeSpan.MinValue.Ticks to TimeSpan.MaxValue.Ticks, which is the same as the range of Int64, which is -9223372036854775808 to 9223372036854775807.
Ticks from a Stopwatch (in the System.Diagnostics namespace) are of varying size, depending on the hardware capabilities of the system. They are usually around 4ns on modern hardware. You can adjust them to TimeSpan ticks by using Stopwatch.Elapsed.Ticks instead of Stopwatch.ElaspedTicks, or by taking the Stopwatch.Frequency into account in your calculations. The range is 0 to Int64.MaxValue.
Tick is a number, there is really not much more validation you can do.
You can check if actual time is in particular range that makes sense for your case, but it is application specific.
Related
I am setting up a system to gather data from a database based on a user inputted start date and end date. The system will gather data averaged over an interval(1 hour, 6 hours, or one day for example). If the user does not input a start or end date I would like the program to set the start date to the current time minus the interval.
I currently have the user inputting the interval in the following format.
1m = 1 minute
1h = 1 hour
12h = 12 hours
3d = 3 days
So these values are not formatted like datetime. I could take the current datetime and subtract it by either minutes, hours, or days depending on the value appended (splitting on the number), but this would mean many if statements. What I would really like is a method to subtract a datetime by an arbitrary value Does anyone have a better solution?
Instead of providing predefined time intervals (that are implemented e. g. via a separate type/enum), it is much easier to let the user freely specify a TimeSpan.
This has two advantages:
The user is not restricted to predefined intervals
You can subtract the TimeSpan directly from your DateTime.Now
If restriction to limited intervals is a requirement, you can implement this in the view/window. But still this should be a TimeSpan.
Consider the following code which attempts to get a DateTime that's equivalent to the local time "midnight yesterday":
DateTime midnightYesterday = DateTime.Today.AddDays(-1.0d);
Will this always result in a DateTime with a time component of 00:00:00 -- regardless of any corner cases such as leap days, leap seconds, or what the local time zone is?
More generally: Does calling DateTime.AddDays, passing a whole number as a parameter, always result in a DateTime being returned that has the exact same time component as the original Datetime?
The MSDN documentation for DateTime.AddDays does not address this specific question.
DateTime does not account for leap seconds. You can read this article from which you will see that because of this it doesn't really support UTC. Documentation states that:
Time values are measured in 100-nanosecond units called ticks, and a
particular date is the number of ticks since 12:00 midnight, January
1, 0001 A.D. (C.E.) in the GregorianCalendar calendar (excluding ticks
that would be added by leap seconds)
About daylight saving time documentation states the following:
Conversion operations between time zones (such as between UTC and
local time, or between one time zone and another) take daylight saving
time into account, but arithmetic and comparison operations do not.
That means that adding days (which is arithmetic operation) to DateTime instance, even if it has kind Local (so represents time in local timezone) does not take DST into account. That makes performing any arithmetic operations on datetimes with kind Local a really bad idea. If you need to do that with date times - first convert it to UTC (that has no notion of DST), perform operation then convert back to local (conversion as stated above does take DST into account).
You can also look at source code to see that datetime value is stored as a number internally (number of ticks) and adding days just adds fixed value to that number. Calculating hour\minute\second use that value and perform fixed operations (just a division) to obtain target value. None of those operations account for anything like leap seconds, time zones or anything else. So the answer to your question is yes.
I did a small winform program for data transferring in Visual Studio, and I used a method to provide the transferring time duration. After the transferring being done, the program will return a dialog window to show the time.
But here I don't know what is the time precision or the resolution of the timer, how can it be such a precision, even micro second?
var startTime = DateTime.Now;
this.transferdata();
var endTime = DateTime.Now;
var timeElapsed = endTime.Subtract(startTime);
when I saw the definition of class DateTime, there is only a precision in milisecond. can anybody tell me why there is such a high resolution timer in the visual studio 2012? Or there is related to the operating system?
The precision of the clock depends on the operating system. The system clock ticks a certain number of times per second, and you can only measure whole ticks.
You can test the resolution for a specific computer using code like this:
DateTime t1 = DateTime.Now;
DateTime t2;
while ((t2 = DateTime.Now) == t1) ;
Console.WriteLine(t2 - t1);
On my computer the result is 00:00:00.0156253, which means that the system clock ticks 64 times per second.
(Note: The DateTime type also has ticks, but that is not the same as the system clock ticks. A DateTime tick is 1/10000000 second.)
To measure time more precisely, you should use the Stopwatch class. Its resolution also depends on the system, but is much higher than the system clock. You can get the resolution from the Stopwatch.Frequency property, and on my computer it returns 2143566 which is a tad more than 64...
Start a stopwatch before the work and stop it after, then get the elapsed time:
Stopwatch time = Stopwatch.StartNew();
this.transferdata();
time.Stop();
TimeSpan timeElapsed = time.Elapsed;
That will return the time in the resolution that the TimeSpan type can handle, e.g. 1/10000000 second. You can also calculate the time from the number of ticks:
double timeElapsed = (double)s.ElapsedTicks / (double)Stopwatch.Frequency;
You are confusing several things. Precision, Accuracy, Frequency, and Resolution.
You might have a variable that is accurate to a billion decimal places. But if you can't actually measure that small of a number then that's the difference between precision and resolution. Frequency is the number of times per second a measurement is taken, while relates to resolution. Accuracy is how closely a given sample is to the real measurement.
So, given that DateTime has a precision much higher than the system clock, simply saying DateTime.Now will not necessarily give you an exact timestamp. There are, however, Higher resolution timers in Windows, and the Stopwatch class uses them to measure time elapsed, so if you use this class you get a much better accuracy.
DateTime has no "default precision". It has only one precision, and that's the Minimum and Maximum values it can store. DateTime internally stores it's values as a single value, and this value is formatted to whatever type you want to display (seconds, minutes, days, ticks, whatever...).
We're making an app which is going to list events across the globe. The events span multiple days.
We want to store the begin and end of the event.
Should I just use 2 DateTime properties and store it all as UTC?
Should we just store the 2 points in time as ticks?
Should we be using a TimeSpan?
Would NodaTime be good here?
Personally I would store everything as UTC time. Since .NET naturally supports converting dates to and from UTC, you don't have to worry about future compatibility. Most databases support storing dates in UTC format. I would also use TimeSpan for code readability when calculating time periods,but storing the datetime as ticks may give you a small performance benefit since you can do comparisons without creating DateTime objects. Depends on how many comparisons you do.
Two datetimes as UTC at rest. Then it will make sense to do operations when you have a start and no end since the event is underway at present. WCF will even automatically make them local times across the wire for you if you like (be sure to set the DateTime.Kind).
DateTimes are ticks internally, so storing them as ticks accomplishes little. They'll be ticks at rest in your DB.
Tuple TimeSpan <long, long, long>;
TimeSpan myTimeSpan = new TimeSpan<start, end, difference>;
You use dot notation to access items like;
long start = myTimeSpan.item1;
The Nth item would be accessed by; myTimeSpan.itemN;
From here if you need UTC time you can easily get it by doing something like;
DateTime startingUTC = new DateTime(myTimeSpan.item1, UTC);
This constructer; public DateTime(long ticks, DateTimeKind kind) will allow you to easily produce DateTime objects in UTC or local time when you need to display the data to the user. Otherwise, it's much easier and more efficient to work with ticks.
What is a good data-type for saving hours in .net?
Is it better to use the decimal type or is the double data-type more appropriate. With hours I mean values such as:
2 for two hours
1.5 for 90 minutes
8.25 for 8 hours and 15 minutes.
A good way to represent a number of hours is to use a TimeSpan:
TimeSpan hours = TimeSpan.FromHours(2);
Given the choice between decimal or double I'd probably go for double as there is typically no expectation that the amount of time is represented exactly. If you need an exact decimal representation of your fractional number of hours (which seems unlikely) then use decimal.
You could also consider storing it as an integer in for example seconds, milliseconds or ticks.
The best datatype to store hours is the one designed for it - TimeSpan.
It has methods that allow you to add/subtract/convert it.
As for storage in a database, it really depends on what you are using this for and what kind of resolution is required.
I would use the time datatype - as it will hold the range:
00:00:00.0000000 through 23:59:59.9999999
However, if you need to hold more than 24 hours in this field, you may want to consider a tinyint or int holding the number of minutes (assuming that is the maximum time resolution you require).
In SQL Server use INT or DECIMAL. TIME isn't really ideal for storing a duration because TIME defines a point in time within the 24 hour clock whereas duration is simply an integer or decimal value. You cannot do addition or subtraction with TIME values and there is no obvious way to use TIME to store durations greater than 24hrs.
Why don't use TIME?
You can use DATEADD with TIME to manipulate it easier:
SELECT DATEADD(minute, 30, CAST('2:00:00' AS TIME))
becomes 02:30:00.0000000. And so on..