Get Ticks per second and convert to String value? - c#

How do I get number of ticks per second of DateTime.UtcNow and convert it to a String value?
BAD QUESTION: try again Get ten millionths of a second

A particular value of DateTime doesn't have a "ticks per second" associated with it; ticks are ticks no matter which DateTime they're in. Ticks are 100 nanoseconds long, so there are 10,000,000 of them per second.
Now to get that as a string is as simple as the string literal "10000000"... although in general you would obtain a number and just call ToString() on it. For instance, you could use:
string ticksPerSecond = TimeSpan.TicksPerSecond.ToString();
Your question is a slightly odd one, so I wonder whether we're missing something... could you edit the question with more details about what you're trying to do. For example, are you trying to determine the number of ticks within the particular second of a particular DateTime? That's most easily done as:
long ticks = dt.Ticks % TimeSpan.TicksPerSecond;

You find the ticks per second as a constant on TimeSpan:
TimeSpan.TicksPerSecond
Not sure what you are trying to do though...
(DateTime.UtcNow.Ticks / TimeSpan.TicksPerSecond).ToString() // Total number of seconds...

I think you may want TimeSpan.TicksPerSecond.
Console.WriteLine("tps = {0}", TimeSpan.TicksPerSecond.ToString());

The number of ticks per second in a DateTime value is always 10000000. One tick is 100 nanoseconds.
So, if you want to convert that to a string:
10000000.ToString()

Related

C# DateTimePicker comparison issue

I want to compare the two dateTimePickers in the winforms using C#.
My comparing code is as below;
if (dtpFromDate.Value > dtpToDate.Value)
{
MessageBox.Show("From Date is greater than To Date");
return;
}
Below are the values of the two dateTimePickers
dtpFromDate.Value = 10/29/2016 5:10:27 PM
dtpToDate.Value = 10/29/2016 5:10:27 PM
But if the two dateTimePickers are set to be at their initial values (i.e. today's date) as above, the if statement got also true, but what I need is to check only if the dates are greater (FromDate>ToDate). Am I doing something wrong?
If you do not care the time, do that:
if (dtpFromDate.Value.Date > dtpToDate.Value.Date)
{
MessageBox.Show("From Date is greater than To Date");
return;
}
To be explicit here, the data type of dtpFromDate.Value is of DateTime. I always prefer to use DateTime.Tick property for DateTime comparisons, since it is an integral type, so the comparison is obvious to the reader and also fast.
I believe when the two different DateTimePicker controls are created, they differ in their values by less than a second, causing the issue. If your intention is to simply compare the DateTime with a least count of second, then you can do this
if ((dtpFromDate.Value.Ticks / TimeSpan.TicksPerSecond) >
(dtpToDate.Value.Ticks / TimeSpan.TicksPerSecond))
{
MessageBox.Show("From Date is greater than To Date");
return;
}
The DateTime object has a least count of a Tick. You can read up on DateTime.Ticks and TimeSpan on MSDN
A single tick represents one hundred nanoseconds or one ten-millionth
of a second. There are 10,000 ticks in a millisecond, or 10 million
ticks in a second.
I had two date time pickers on the same windows form. Even though I was making a comparison of dtpStartDate.Value.Date and dtpEndDate.Value.Date, the check for the end date being earlier than the start date was still coming up wrong when it appeared that the two date time picker values were the same. It wasn't until I compared the values down to the millisecond like dtpEndDate.Value.ToString("MM/dd/yyyy HH:mm:ss.fff") and dtpStartDate.Value.ToString("MM/dd/yyyy HH:mm:ss.fff") that I saw the difference.
In my case I wanted to only compare month, day and year. What I had to do to make a proper comparison was use
if (dtpStartDate.Value.Date.Date > dtpEndDate.Value.Date.Date)
{
// Start Date cannot be later than the End Date
}

Calculate length of time between two times in AM/PM

I have three DrowDownLists for selecting start time and another three for selecting end time. I need an asp.net program which will give duration between two time and after i entered start time then end time should be greater than start time. First DrowDownList contains 1 to 12 hours and second contains 0 to 59 minutes and third one is for selecting am/pm.
I don't know where to start in codebehind.
You could first turn your strings into TimeSpan, try out TimeSpan.Parse:
https://msdn.microsoft.com/en-us/library/se73z7b9(v=vs.110).aspx
With two TimeSpan objects, you will be able to calculate durations without having to worry on how to do it. To get the duration between two timespans, try out TimeSpan.Subtract:
https://msdn.microsoft.com/en-us/library/system.timespan.subtract(v=vs.110).aspx
hope this helps!

Casting and Convert.ToInt32() behave different in C#?

Here a simple C# piece of code:
Convert.ToInt32(TimeSpan.FromMinutes(5).TotalMilliseconds);
//which brings me 300000
(int)TimeSpan.FromMinutes(5).Milliseconds;
//which brings me 0
Why would casting (int) result is different when compared to Convert.ToInt32()?
Shouldn't both bring the same result?
In the first version you're using the TotalMilliseconds property - in the second you're using Milliseconds.
To give a simpler example, with no casting or calling to Convert.ToInt32:
TimeSpan ts = TimeSpan.FromHours(49);
Console.WriteLine(ts.Hours); // 1 (it's two days and one hour)
Console.WriteLine(ts.TotalHours); // 49 (it's 49 hours in total)
The milliseconds is just the milliseconds PORTION of the 5 seconds. Use TotalMilliseconds on the second one as well.
In you first example you use TotalMilliseconds and then just Milliseconds.
Your error is that in the second example you are calling the .Milliseconds property, not the .TotalMilliseconds property.
The former returns 5 minutes in milliseconds. The latter returns the millisecond portion of 5 minutes, which is zero.
The cast vs. convert is a red herring!
You left out "Total" from the second line. So, this works.
(int)TimeSpan.FromMinutes(5).TotalMilliseconds;
They're the same... you've used TotalMilliseconds vs Milliseconds. The first is the total number of milliseconds in 5 minutes, whereas the second is the remainder, or the value which would be displayed if you wanted to display the time IE the '000' in '00:05:00.000'
The issue is not the conversion but that you are comparing TotalMilliseconds and Milliseconds!

How to get current Time with Milli second precision ( C#)

I use System.DateTime.Now , but it return like 5/28/2011 1:45:58 AM .(no Milli second precision)
I would like to save current time (or Date time ) with Milli second precision in database .
Update : Sorry , I meant Milli Second
System.DateTime manages precision to the millisecond, 5/28/2011 1:45:58 AM is just how it was formatted to a String.
To format with millisecond included use format string: "d/M/yyyy hh:mm:ss.fff tt"
If you want to store it in a SQL Server database, ADO.Net automatically converts the CLR System.DateTime datatype to a SQL Server datetime datatype (and vice-versa).
The CLR System.DateTime has 100-nanosecond precision (e.g., each tick is 100 nanoseconds; 10,000 ticks per millisecond, 10 million ticks per second.
The SQL Server datetime datatype is precise to (approximately) 3ms.
You shouldn't need to worry about it: ADO.Net will take care of it for you.
OTOH, if you really want to throw away extra nanoseconds, something like this ought to do the trick:
public static DateTime ToExactMillisecondPrecision( DateTime dt )
{
const long TICKS_PER_MILLISECOND = 10000 ;
long totalMilliseconds = dt.Ticks / TICKS_PER_MILLISECOND ;
return new DateTime( totalMilliseconds * TICKS_PER_MILLISECOND ) ;
}
Can't really see the need myself.
Look under the properties list in this link. All the different options are there.
http://msdn.microsoft.com/en-us/library/system.datetime.aspx
Including seconds, milliseconds, and ticks
The string you posted contains seconds, so I suppose you're not asking for second precision, but for more precise timing.
The value of DateTime.Now is returned with more than millisecond precision. it's just that with default formatting, the milliseconds aren't displayed. To display the value with milliseconds, you can either use the o standard format string, or write your own custom format string, that includes the millisecond format specifier fff.
Note that just because the returned value is precise, it doesn't mean it's as much accurate. The actual accuracy is not defined exactly, but tends to be in tens of milliseconds.
It should not be necessary to convert the date to string. Perhaps the real problem is that you using dynamic SQL.

What is a meaningfull datatype to save hours

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..

Categories

Resources