Millisecond is not removed from data - c#

I have a DateTime column in my table. I want to store RUN date without millisecond stamp.
I tried below code, but in table, millisecond comes as 0000000.
Is that possible to store only date in "2021-06-09 08:58:03" format?
DateTime dt = Convert.ToDateTime(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
Thanks in advance. Any help will be appreciated.

Upfront
Decide if you want to store a SQL datetime (or related) type or just a formatted string representation of a date and time.
Also decide if you want to use a local clock (of client workstation or even web server, with a clock that may be in a time zone different from your database server or maybe just out of time-sync with the database server).
Because
If the need is to be able to audit/report/coordinate the "order of events" you should choose an appropriate SQL type like datetime/datetime2/smalldatetime and instead of using client-side code to query the client-side clock, use SQL DATE and TIME functions MS T-SQL date and time types and functions. If you do this then record values at whatever precision they are offered and worry about string formatting when values are retrieved for display.
Only if you wish to store a string representation of a date and time in the database should you concern yourself with format at the time of insertion.
Final Answer
Consider a floating point numeric type like C#'s double. You can declare double d1 = 1.23E+2; or double d2 = 123. Both d1 and d2 contain an equal value (approximately 123.00...0 with about 13 zeroes all of which are significant). The format used at the time of assignment cannot influence future use of the value or system behaviour when it is used, whether for arithmetic or display purposes. The same applies to date and time types.
#mjwills comment taught me something I wasn't aware of: datetime2(0) seems to offer what you want - date and time with a precision of whole seconds, however fractions of a second are still recorded (try insert value CURRENT_TIMESTAMP to a datetime2(0) column), so treat the precision parameter as a storage-allocation hint rather than a hard limit on "significant digits recorded" and you will still need to worry about formatting values when retrieved for reporting/display.

Related

Round DateTime using SQL DATETIME rules

Say there is some code that compares a DateTime object with a DateTime object that has been saved and returned from SQL Server, stored in a DATETIME object.
The comparison is done on hh:mm:ss-equality, but it is possible that SQL Server 'changes' the second component when saved which makes the comparisons fail ~1.5/1000 of the time or so.
This is because SQL Server will round/truncate this value when saved in the database as a DATETIME value:
datetime values are rounded to increments of .000, .003, or .007 seconds..
Is there a (standard) C#/.NET function that does the same rounding?
The primary goal of this question is to normalize the value prior to saving, for use in comparisons. That is, F(original) == F(saved) should always be true.
The final goal overall is to ensure the values are saved 'within the correct second', such that hh:mm:01.999 is stored as hh:mm:01.997. This would allow the hh:mm:ss-equality comparisons to be reliable regardless of if done to the original DateTime values or restored values. In this case, original.Second == F(original).Second should always be true as well.
For better or worse, one widely-used assumption is the comparison is done per hh:mm:ss, so a simple epsilon-compare of 2 milliseconds is out; although I wouldn't be opposed to a strongly-argued for comparison function that might also solve the final goal.
The SqlDateTime structure stores date/time values in the same way as SQL Server's datetime type. It provides conversions from and to the .NET DateTime type, and rounds when the conversion is performed.
Note that you have contradictory requirements in your question. You say you want the same rounding as SQL Server. You also say you want the rounding to never change the "second" component. You can't have it both ways. If you need the "second" component to not change, you may need to implement that yourself. You can check after the conversion has been done whether the second changed, and then restore it, or you may implement the conversion yourself to always round down.

Type to store time in C# and corresponding type in T-SQL

I would like to know how to store time in C# and T-SQL. I know that both of them provide a DateTime type but I just need to store a time. For instance:
var startTime = 9PM;
var endTime = 10PM;
And then store/retrieve this values from a database. Thanks in advance.
Francesco
C#
Whether to use a DateTime or TimeSpan type in C# to store 9 PM is up to taste. Personally, I'd use DateTime, leaving the date component empty, since that's semantically closer to what you want. (A TimeSpan is designed to hold time intervals, such as "21 hours".)
The documentation supports both options. This is from the documentation of TimeSpan:
The TimeSpan structure can also be used to represent the time of day, but only if the time is unrelated to a particular date.
On the other hand, the MSDN article Choosing Between DateTime, DateTimeOffset, and TimeZoneInfo mentions the following:
The DateTime structure is suitable for applications that do the following:
* Work with dates only.
* Work with times only.
[...]
T-SQL
SQL Server has a time data type.
In C# there is not a type to hold only a time. There is TimeSpan, but it's intended to keep a period of time and not really a component of a DateTime (i.e. hours and minutes) only.
Starting with SQL Server 2008 there is a time type (Using Date and Time Data) that does only store a time component.
EDIT: Misread your question at first. TimeSpan is exactly what you're looking for and it can be stored in a time type with SQL 2K8.
In C# you'd probably want to use a TimeSpan structure if you just wanted to store a time interval. However, you seem to want to appear to store a start-time and an end-time, which would require storing two values. You could, therefore, use two TimeSpans (based on, say, number of minutes from midnight to represent the time) or you could just use two DateTime values and throw away the date component.
As has been noted, SQL Server 2008 has a Time datatype, but this isn't available in earlier versions which only have DateTime. You could also just store an Int representing number of minutes past midnight which can be easily converted to a TimeSpan (TimeSpan interval = TimeSpan.FromMinutes(60)).
Timespan in c# is how you manipulate time intervals. Contrary to what other posters are saying i don't think the Time data type is correct for storing time intervals in SQL, unless you actually want to store the start time and end time and not the time interval (i.e. 1 hour in you example). It is for storing a time of day, a bit like a DateTime but with no date. When i want to store a time interval in SQL I just use an int and then have it represent a unit of time appropriate to what I am trying to do (e.g.minutes, seconds, milliseconds etc. )

How to specify a 12-hour time format in SQL Server 2008

I am using SQL Server 2008 and I have a database file (mydata.mdf) in which I have a column in one of the table and that column has the datatype (Time) .
I added this database file to my WPF-C# project (using VS2010) , but I had a problem and its as follows :
This (Time) column treats time in 24-Hours system , but I want to use (12-Hour) system in my application , so is there a way to define a 12-Hour system time in SQL server2008 .
and if there isn't , what do you think is the best way to handle that ???
Pleeeeeeeeeeease help me ASAP because I'm in a hurry and I can't figure it out ...
The time in the database is not "formatted". It is represented in some internal format (which you can Google for but shouldn't care about) that allows it to represent each moment in the day, to the supported level of precision.
The values are only formatted when your application converts them to strings for the purpose of displaying them to the user, and you have full control over this.
So if you have read a time into an instance of the CLR DateTime class, you can display as a 12-hour time (omitting the date) with value.ToString("h:mm:ss tt"). Custom formatting options are listed here.
The answer is you can't really, but don't worry, it's not a problem. Format the date in your C# code.
The point is that a date and time is an absolute value, which is what you want SQL to store, then 12 hour vs 24 hour clock is merely a display detail, eg, 13:00 and 1:00pm are equivalent, don't worry about how SQL stores it, then in C# use the following to display it:
DateTime myDateTime = GetTheTimeFromSomeMethod();
myDateTime.ToString("h:mm:ss tt");
There are lots of guides, This is a good one, but there are plenty of others eg this one
Does it have to be formatted from the database? C# and WPF both provide many built-in date format options. For example, check out the ContentStringFormat property on a Label.
If you must do it in the database, here is a messy workaround which will work
It formats the date as a string using a 12h clock, then removes the date part of it
select right(convert(varchar, cast('1/1/2010 23:59:59' as datetime), 100),
charindex(' ', reverse(convert(varchar, cast('1/1/2010 23:59:59' as datetime), 100)))-1)

Converting/Searching GETUTCDATE()

If I store all my dates in SQL Server 2005 as GetUtcDate() what is the best way to search on these date fields. I'm using C# so should i convert the date submitted by the user to UTC using C# (passing to Stored Proc) to search my dates in SQL?
Also, since i'm using UTC do I need to worry about day light savings? When I want to display the date/time to the user/view do I simply just add/subtract the offset? Is there anything to look out for when converting my UTC date/time from the database to the user timezone for display?
Dealing with time zones is a major pain in the #$$. One thing to consider is that Windows only stores the current DST rules, not historic rules. So if you are relying on the rules to be able to accurately recreate the old values, you might find some discrepancies in your data. DST rules change all the time. Some countries don't even have set rules, they just announce the dates every year.
If you cannot afford discrepancies in your data, you might be better off storing the date as a string with the time zone information encoded in it. In .Net you can use DateTime.ToString("O"). This format is culture agnostic so you will always get the same format no matter what culture the code is running in.
var origDt = DateTime.Now;
var dtStr = origDt.ToString("O");
var newDt = DateTime.Parse(dtStr, null, System.Globalization.DateTimeStyles.RoundtripKind);
Console.WriteLine(dtStr);
if (newDt == origDt)
Console.WriteLine("Dates equal"); // should be true
else
Console.WriteLine("Dates not equal");
Check out the MSDN documentation for more information on this format style.
Of course this comes at a cost. It will be inefficient to search the database by date (it can be done, but the strings need to be converted to dates). Chances are the time zone differences won't matter too much anyway. It really depends on what you are doing with the data and how important accuracy is.
You might want to make sure that the project actually requires UTC and time zones before you go down this path. There is a decent chance that just storing the time from the local computer and ignoring time zones is good enough.
"should i convert the date submitted by the user to UTC using C# (passing to Stored Proc) to search my dates in SQL?" - Sounds like a good idea
"since i'm using UTC do I need to worry about day light savings?" - no, C# will take care of that when you're converting between local and UTC time.
Don't just add/subtract the offset, use the C# DateTime functions to convert between UTC and local time. That way it'll take care of DST.

Handling and storing elapsed time

I'm having problems deciding on what is the best way is to handle and store time measurements.
I have an app that has a textbox that allows the users to input time in either hh:mm:ss or mm:ss format.
So I was planning on parsing this string, tokenizing it on the colons and creating TimeSpan (or using TimeSpan.Parse() and just adding a "00:" to the mm:ss case) for my business logic. Ok?
How do I store this as in a database though? What would the field type be? DateTime seems wrong. I don't want a time of 00:54:12 to be stored as 1901-01-01 00:54:12 that seems a bit poor?
TimeSpan has an Int64 Ticks property that you can store instead, and a constructor that takes a Ticks value.
I think the simplest is to just convert user input into a integer number of seconds. So 54:12 == 3252 seconds, so store the 3252 in your database or wherever. Then when you need to display it to the user, you can convert it back again.
For periods less than a day, just use seconds as other have said.
For longer periods, it depends on your db engine. If SQL Server, prior to version 2008 you want a datetime. It's okay- you can just ignore the default 1/1/1900 date they'll all have. If you are fortunate enough to have sql server 2008, then there are separate Date and Time datatypes you can use. The advantage with using a real datetime/time type is the use of the DateDiff function for comparing durations.
Most databases have some sort of time interval type. The answer depends on which database you're talking about. For Oracle, it's just a floating point NUMBER that represents the number of days (including fractional days). You can add/subtract that to/from any DATE type and you get the right answer.
As an integer count of seconds (or Milliseconds as appropriate)
Are you collecting both the start time and stop time? If so, you could use the "timestamp" data type, if your DBMS supports that. If not, just as a date/time type. Now, you've said you don't want the date part to be stored - but consider the case where the time period spans midnight - you start at 23:55:01 and end at 00:05:14, for example - unless you also have the date in there. There are standard build in functions to return the elapsed time (in seconds) between two date-time values.
Go with integers for seconds or minutes. Seconds is probably better. you'll never kick yourself for choosing something with too much precision. Also, for your UI, consider using multiple text inputs you don't have to worry about the user actually typing in the ":" properly. It's also much easier to add other constraints such as the minute and second values conting containing 0-59.
and int type should do it, storing it as seconds and parsing it back and forth
http://msdn.microsoft.com/en-us/library/ms187745.aspx

Categories