sql datetime parameter problem - c#

HI all,
I am passing the date parameter as like this:
DateTime date = DateTime.Now;
date.ToString("YYYY-MM-DD 00:00:00:000");
But getting this exceptions:
System.Data.SqlTypes.SqlTypeException: SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM. at System.Data.SqlTypes.SqlDateTime.FromTimeSpan(TimeSpan value) at System.Data.SqlTypes.SqlDateTime.FromDateTime(DateTime value)

There should be a decimal dot between the seconds and the milliseconds. The format string is case sensitive. Try:
date.ToString("yyyy-MM-dd")
or
date.ToString("yyyy-MM-dd HH:mm:ss.fff")
Also ask yourself whether you really need to convert arguments to strings. It smells odd and it may not be necessary. If you want to pass only the date and not the time, then pass the Date property of your DateTime object as your parameter value. Keep it strongly-typed to avoid SQL-injection, performance and type conversion issues.

No parameter is being passed in here, the code sample you have posted is incomplete by looking at the resulting SqlTypeException
Also the date format should be:
date.ToString("yyyy-MM-dd HH:mm:ss:fff")

If you are trying to ignore the time portion (hence your zeros) try
date.ToString("yyyy-MMM-dd");
If you want the time portion too ...
date.ToString("yyyy-MMM-dd hh:mm:ss.fff tt");
Note both have 3 Ms for the month which makes them unambiguous strings that SQL should be able to parse and cannot misinterpret.
But, why not just pass the value as a date object rather than convert to a string?

Related

Inconsistency when parsing DateTime in the same format

I have the following strings:
10/10/2021 00:00:00 and 18/11/2021 23:59:59
I have this code:
bool first = DateTime.TryParse("10/10/2021 00:00:00",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out DateTime firstDate);
bool second = DateTime.TryParse("18/11/2021 23:59:59",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out DateTime secondDate);
Console.WriteLine(firstDate + " --- " + secondDate);
The output is:
10/10/2021 12:00:00 AM --- 1/1/0001 12:00:00 AM
As you can see the second date is not properly parsed, even though it's in the same format. What is the reason for that and how can I fix it?
As you can see the second date is not properly parsed, even though it's in the same format.
Here my two cents.
Programming languages and frameworks are not smart enough to know which kind of format data you applied, specially for dates, times, numbers etc.. If you provide these data, you kinda have to provide the proper format as well so they can do their job. You "said" the same format, but you didn't apply any format in your code. So, as we humans, we know (at least you told us) but the computer don't know.
Let's look what TryParse(String, IFormatProvider, DateTimeStyles, DateTime) documentation says;
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified culture-specific format
information and formatting style, and returns a value that indicates
whether the conversion succeeded.
You didn't supply format information you supplied IFormatProvider as InvariantCulture. So, what are these "culture specific formats"?
Well, most of them are returns with GetAllDateTimePatterns method (but not all of them) but be aware because documentation says;
You can use the custom format strings in the array returned by the
GetAllDateTimePatterns method in formatting operations. However, if
you do, the string representation of a date and time value returned in that formatting operation cannot always be parsed successfully by the
Parse and TryParse methods. Therefore, you cannot assume that the
custom format strings returned by the GetAllDateTimePatterns method
can be used to round-trip date and time values.
So, if you run;
CultureInfo.InvariantCulture.DateTimeFormat.GetAllDateTimePatterns().Dump();
*Dump is just an extension method of LINQPad by the way, it just outputs to the console.
You will get a lot of datetime patterns, but for our case, the important one is we get MM/dd/yyyy HH:mm:ss format for InvariantCulture.
As you can see, your 18/11/2021 23:59:59 data doesn't match with MM/dd/yyyy HH:mm:ss format because there is no 18th month on Gregorian calendar which is a DateTime instance belongs internally.
Your second parsing fails by the way, that's quite different just saying "the second date is not properly parsed" and this is how DateTime.TryParse method works as explained in the documentation;
When this method returns, contains the DateTime value equivalent to
the date and time contained in s, if the conversion succeeded, or
MinValue (which is 1/1/0001 12:00:00 AM) if the conversion failed. The conversion fails if the s
parameter is null, is an empty string (""), or does not contain a
valid string representation of a date and time.
So, best way to handle this to supply a "specific" format using with DateTime.TryParseExact method or one of its overloads like;
bool first = DateTime.TryParseExact("10/10/2021 00:00:00",
"dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out DateTime firstDate);
bool second = DateTime.TryParseExact("18/11/2021 23:59:59",
"dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out DateTime secondDate);
The default DateTime format is 'MM/dd/yyyy' and since you have the date in 'dd/MM/yyyy' format it gives you the output.
Maybe try changing the date format input as 11/18/2021 23:59:59

encountering String was not recognized as valid datetime using ParseExact

I want to insert the DateTime.Now as dd-MMM-yyyy format, but it is giving me string is not recognized as valid datetime while I use ParseExact.
db.AddInParameter(objdbCommand, "#dtAddedOn", DbType.DateTime, DateTime.ParseExact(Convert.ToString(DateTime.Now), #"dd-MMM-yyyy", System.Globalization.CultureInfo.InvariantCulture));
I have also tried :
DateTime.ParseExact(Convert.ToString(DateTime.Now), #"dd-MMM-yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture));
but it is giving me the same error
Since you are inserting a DateTime anyway, you do not need to Convert to string and parse back to DateTime.
db.AddInParameter(objdbCommand, "#dtAddedOn", DbType.DateTime, DateTime.Now);
will do the trick.
DateTime does not have a format. Format comes into play as soon as you need a textual representation of the value that the DateTime represents. I also wouldn't recommend to use Convert for this but one of DateTime.ToString overloads.
Edit:
If you do not want to include the Time part, i.e. insert the Date, only you can use DateTime.Now.Date (see Date Property) or even easier DateTime.Today. This will give you a DateTime object with Time components all set to zero.
Edit 2:
Mind that there are some inherent problems using DateTime, especially if your system is going to be used spanning different TimeZones. Going deeper into this would go beyond the scope of this answer, though. Just want to give you a heads-up.
You may want to checkout DateTimeOffset and related Articles like Choosing between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo

Converting DateTime throws SqlDateTime overflow

Currently I've a string with a date and time. When I show the string it looks like:
2015-06-16 09:17:28 PM
But when I try to put it into the database it's telling me:
Additional information: SqlDateTime overflow. Must be between 1/1/1753
12:00:00 AM and 12/31/9999 11:59:59 PM.
I've to convert the string. So there is now other way!
What's the right way to do this? Obviously the value in database is datetime.
This is my code (I've put it together actually it's from multiple classes):
string time = date + " " + txtTime.Text;
DateTime temp = Convert.ToDateTime(time);
String query ="insert into reserveringen (reserveringId,klantId,medewerkerId,aantalPersonen,begintijd,eindtijd)values(#reserveringId,#klantId,#medewerkerId,#aantalPersonen,#begintijd,#eindtijd)";
SqlCommand comm = sqlCrud.returnSqlCommand(query);
comm.Parameters.AddWithValue("begintijd",temp);
I already googled a lot.... but nothing works.
Thanks
You should not use Convert.ToDateTime like that. You should use DateTime.Parse or DateTime.ParseExact.
DateTime temp = DateTime.ParseExact(time, "yyyy-MM-dd hh:mm:ss tt", CultureInfo.InvariantCulture);
Since DateTime.Parse(temp) worked for you, you can leave it as that.
Edit:
The difference between the two methods is very important in this situation.
Convert.ToDateTime(s)
This method will call DateTime.Parse internally with the following parameters:
DateTime.Parse(s, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None);
Now, DateTime.Parse(s) does something a little different:
DateTime.Parse(s, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.AllowWhiteSpaces);
The difference is the DateTimeStyles flag. This flag completely changes the output. The Convert.ToDateTime(s) was likely returning a DateTime.MinValue object, which is what it does when it encounters a null string. (I can only guess without spending more time on research, but that result makes sense, as DateTime.MinValue is 1/1/0001 12:00:00 AM, which is outside the range SQL expects.)
References:
http://bytes.com/topic/c-sharp/answers/482419-convert-todatetime-vs-system-datetime-parse
https://msdn.microsoft.com/en-us/library/system.datetime.parse(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.datetime.minvalue(v=vs.110).aspx
Both
DateTime.Parse("2015-06-16 09:17:28 PM");
And
Convert.ToDateTime(date);
will return the same DateTime value.
I would try to focus on the query.
Note that you might be passing a value from C# that resolve in the minimum value for DateTime (1/1/0001 12:00:00 AM) which is out of range for DateTime value on SQL Server.

convert date string to datetime

I have date string in format dd-MMM-yyyy and want to convert this to datetime, when I use below code
DateTime.ParseExact("20-Oct-2012", "yyyy-MM-dd HH:mm tt", null)
it causing an error
String was not recognized as a valid DateTime.
When I modify above code
DateTime.ParseExact("20-Oct-2012", "dd-MMM-yyyy", null)
then I got date time in format (mm/dd/yyyy) : 10/20/2012 12:00:00 AM
But I need it should be converted in yyyy/mm/dd format. Please help me in this regard.
You should try this
DateTime.ParseExact("20-Oct-2012", "dd-MMM-yyyy", null).ToString("yyyy/mm/dd")
For further reading on formats Check This
You need to distinguish between two separate concerns: that of parsing your original string into an abstract DateTime representation, and that of converting the latter back into another string representation.
In your code, you're only tackling the former, and relying on the implicit ToString() method call (which uses the system's current locale) to convert it back to string. If you want to control the output format, you need to specify it explicitly:
// Convert from string in "dd-MMM-yyyy" format to DateTime.
DateTime dt = DateTime.ParseExact("20-Oct-2012", "dd-MMM-yyyy", null);
// Convert from DateTime to string in "yyyy/MM/dd" format.
string str = dt.ToString("yyyy/MM/dd");
Also note that the mm format specifier represents minutes; months are represented by MM.
Edit: 'Converted date contain value "10/20/2012 12:00:00 AM".' Be careful what you mean by that. The constructed DateTime value contains an abstract representation of the parsed date and time that is independent of any format.
However, in order to display it, you need to convert it back into some string representation. When you view the variable in the debugger (as you're presumably doing), Visual Studio automatically calls the parameterless ToString() method on the DateTime, which renders the date and time under the current culture (which, in your case, assumes the US culture).
To alter this behaviour such that it renders the date and time under a custom format, you need to explicitly call the ToString(string) overload (or one of the other overloads), as I've shown in the example above.
You could try this instead :
Convert.ToDateTime("20-Oct-2012").ToString("yyyy/MM/dd")
Hope this will help !!

String to mmm-yy format of time in C#

I need to perform some date operations in ASP.net using C#.
The date i would enter should be of format 'Jul-05' (mmm-yy Format and type-string)...
how can i check with this????
Or how can i validate this with whatever user is entering as a string???
After validating that, i need to compare tht with a value in Database(say a column name buy_period which has a value (say) 04/31/2007).
How can i write a Query for comparing both?? (as both dates would be of different formats)
Can u pls help me in this ???
DateTime myDateTime = DateTime.ParseExact( input, "MMM-yy" );
You can then happily pass it to a stored procedure (etc.) as a parameter to do your comparison on the server (or just use the DateTime returned as the result of an existing query)
Use the TryParseExact method to validate the string and parse it to a DateTime value:
DateTime month;
if (DateTime.TryParseExact("MMM-yy", CultureInfo.InvariantCulture, DateTimeStyles.None, out month)) {
// parsing was successful
}
The DateTime value will use the first day of month and the time 0:00 to fill up a complete value, so a string like "jul-05" will be parsed into a complete DateTime value like 2005-07-01 00:00:00.0000, so it will be the starting point of that month.
To compare this to a date in the database you also need the starting point of the next month, which you get with:
DateTime nextMonth = month.AddMonths(1);
Now you can just compare a date to the starting and ending point of the month in this manner:
where date >= #Month and date < #NextMonth
The .NET framework has some nice methods on the DateTime struct :: Parse, TryParse, ParseExact, TryParseExact.
This info is discussed on MSDN.
Becuase you're providing a custom date string, we should then use the ParseExact or TryParseExact. The later doesn't throw an exception if it fails to parse.
So.. lets try this...
using System.Globalization;
CultureInfo MyCultureInfo = new CultureInfo("en-US");
string myString = "Jul-05";
DateTime myDateTime = DateTime.ParseExact(myString, "MMM-yy", MyCultureInfo))
Console.WriteLine();
the value myDateTime can then be passed to a database as a DateTime property and checked against that.
EDIT: Damn, beaten by Rowland by a min, as i was typing it!
EDIT 2: Please note the "MMM-yy". As stated on the MSDN page, MMM is "Represents the abbreviated name of the month as defined in the current System.Globalization.DateTimeFormatInfo.AbbreviatedMonthNames property." mmm (lower case) is invalid.
1: read this
2: is the column is a datetime or varchar?
well your validation and comparison have to be two different operations. so you could do alot of things for validation.
Validation Options:
1.) Split your string on "-" and check to see if the mmm part is in your list of months, and then check to see if the number is valid.
2.) Regular Expression, this is advanced but can be reduced to one line. Look up RegEx if you are interested.
After you've validated the string, convert it to a DateTime object and compare it to the other value using DateTime.Compare().
Hope that helps.
You could use
DateTime date = DateTime.ParseExact(value, "MMM-yy", null); //checked at http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
and then use that date in a sql command parameter.

Categories