Welcome to the Lounge
The Lounge is rated PG. If you're about to post something you wouldn't want your
kid sister to read then don't post it. No flame wars, no abusive conduct, no programming
questions and please don't post ads.
|I usually just save
DateTime.Now for a DB transaction into some
datetime field. If a report or UI needs to show the date/time, it's formatted accordingly, for example
MM/dd/yyyy HH:mm:ss tt (for us US people).
So, I have a "When checked in" (start time) and I have a "When checked out" (stop time) for tracking employee hours worked. And I compute the hours/minutes/seconds worked basically as "check out time" - "check in time", displayed as "hh:mm:ss" (they don't work more than 24 hours, haha.)
So, on occasion, my time worked is off by 1 second comparing start time and stop time as hh:mm:ss.
Why? Because I of the millisecond component to date/time!
So I coded:
DateTime now = DateTime.Now;
now = now.AddMilliseconds(-now.Millisecond);
which works fine, particularly since the DB stores only 3 digits for the ms component, but out of curiosity, I google "getting DateTime without milliseconds" and come across this SO page.
And I wonder, WTF is all this crazy stuff they're doing. Lower down, I find my solution, and I read this:
The Millisecond property gives an integer between 0 and 999 (inclusive). So if the time of day before the operation was, say, 23:48:49.1234567, then that integer will be 123, and the time of day after the operation is 23:48:49.0004567. So it has not truncated to a whole number of seconds.
OMG. Seriously? OK, I guess that makes sense because underlying
DateTime is actually
Ticks, so subtracting off just the integer portion of the ms isn't necessarily going to give me an actual tick at exactly the second.
And to make things more complicated, there's the "Kind" -- Local, UTC, or undefined. Oh good grief.
So I'm going with the solution in one of the earlier SO posts that looks like this:
new DateTime(date.Ticks - (date.Ticks % resolution), date.Kind);
The lesson learned (over and over) is that you think something is simple, and it isn't.
The other lesson learned is, thank God for people smarter than me!
Latest Article - A Concise Overview of Threads
Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you.
Artificial intelligence is the only remedy for natural stupidity.
modified 15-Sep-18 17:59pm.
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
Copyright © CodeProject
All Rights Reserved.