I have a datetime field like
{01/01/0001 00:01:02}
Millisecond = 30 and the Ticks for the above datetime field is
6203000000
The ticks save in the database as an int value which is 62030. I need to reproduce the above date time using the value in the database (62030). So I tried the following.
var data = 62030;
winTime = new DateTime().AddTicks(Convert.ToInt64(data.ToString().PadRight(10, '0')));
var b = winTime.Ticks;
var b = 6203000000. But it returns minute as 10 instead 01, second as 20 instead of 02 and Millisecond as 300 instead of 030.
Can anyone see what I'm doing wrong?
It seems to me that your "ticks 62030" is actually "milliseconds 62030" in which case it's very simple - you just need to multiply by "the number of ticks per millisecond" which is 10,000. You don't need to use DateTime
for this at all:
// Note that if you want any significant length of time, you'd expect to get
// the data as a long, not an int
int data = 62030; // Milliseconds
long ticks = data * 10000L;
... and you certainly don't need string conversions. Converting to a string, padding, and then converting back again is a very tortuous and error-prone way of performing multiplication.
Or if you do need a DateTime
:
int data = 62030; // Milliseconds
long dateTime = new DateTime(data * 10000L);
I strongly suspect that any DateTime
value that early should actually be treated as a TimeSpan
though - what's this really meant to represent? If so, it's even easier:
TimeSpan ts = TimeSpan.FromMilliseconds(data);
Date and time concepts are very easy to mix up, and you end up with some very subtle bugs. Personally I'd recommend using my Noda Time project which separates them more than .NET does, but even if you don't use the library it's worth looking at the list of concepts so you can think about them appropriately within .NET too.
Why not just use the DateTime
constructor that accepts an Int64
representing ticks, such that:
var dateTimeFromTicks = new DateTime(ticks);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With