SqlDateTime overflow error with parsing Date in SQL Server - c#

I am trying to save date from C# to SQL Server. First want to display Date format as dd/MM/yyyy to the user. then after selecting the date on Winforms screen. I want to save it to database. If I remove datetimePicker1.CustomFormat line in the code it is saving fine to the database. But I want to display the date format as dd/MM//yyyy. How to solve this?
I'm getting this error:
SqlDateTime overflow.Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
Code:
//c#
DateTime fromDate;
public void SetMyCustomFormat()
{
// Set the Format type and the CustomFormat string.
//dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "dd/MM/yyyy";
DateTime.TryParse(dateTimePicker1.Text, out fromDate);
fromDate = fromDate.Date;
}

You didn't include any code of where you are using this value with respect to SQL Server, however the error is likely due to the D/M/Y format. This will cause a problem on, for example, Dec 31 because it will be passed as text 31/12/2014 which typically causes problems when converting to a date (depending on locale settings).
For your case just use the DateTimePicker.Value property to extract the date. This will return a DateTime type so you don't have to parse the value.
DateTime fromDate;
public void SetMyCustomFormat()
{
// Set the Format type and the CustomFormat string.
dateTimePicker1.CustomFormat = "dd/MM/yyyy";
fromDate = dateTimePicker1.Value.Date;
}

The Sql DateTime and the C# DateTime types have different valid date ranges (hence they aren't fully compatible).
Sql Datetime only support January 1, 1753, through December 31, 9999.
The issue is that your TryParse is failing causing fromDate to be 1/1/0001 which the Sql DateTime type doesn't support.
In SQL use DateTime2 and always validate the success of the parse.
http://msdn.microsoft.com/en-us/library/ms187819.aspx
http://msdn.microsoft.com/en-us/library/bb677335.aspx
UPDATED:
And the reason your TryParse is failing is because it is expecting the format mm/dd/yyyy. Instead of using TryParse use:
bool success = DateTime.TryParseExact(dateTimePicker1.Text,
"dd/MM/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out fromDate);

Related

String with dd/MM/yyyy format to Date time irrespective of System date time format [duplicate]

I need convert the date of string format 'MM/dd/yyyy' to datetime format 'MM/dd/yyyy' when the system date format is 'dd/MM/yyyy'.
DateTime stores a date as a numerical value, not as a string. So asking for a DateTime type of format 'MM/dd/yyyy' doesn't make much sense. If you are displaying the date in a WPF control, it will default to displaying a string that conforms to the system date format. But that is just a display string that you can manipulate using the format strings alluded to in the links above. Using #Sajeetharan's code will create a DateTime struct with the correct value internally. How you display it is up to you and your string formatting choices.
The same goes for dates stored in a database column of type 'datetime'. The value is stored numerically. Your query editor will display the value likely in the same format as your system settings. If the date is stored as a string, then again, #Sajeetharan's code is the correct way to convert the database string into a DateTime struct.
use DateTime.ParseExact
DateTime.ParseExact("05/02/2014", "dd/MM/yyyy", CultureInfo.InvariantCulture)
.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
This may help:
string dateString="05/02/2014";
DateTime txtmyDate = DateTime.ParseExact(dateString, "MM/dd/yyyy",
CultureInfo.InvariantCulture);
try this
string dateString="05/02/2014";
DateTime txtmyDate =convert.toDateTime(dateString);
DateTime dt = DateTime.ParseExact("05/02/2014","MM/dd/yyyy",CultureInfo.InvariantCulture);

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.

Format Exception - string not recognized as a valid DateTime

I have an issue similar to this > Format exception String was not recognized as a valid DateTime
However, my spec requires a date format of ddMMyyyy, therefore I have modified my code but I am still getting the same error
DateTime now = DateTime.Now;
DateTime dt = DateTime.ParseExact(now.ToString(), #"ddMMyyyy", CultureInfo.InvariantCulture);
I am unclear why.
You code fails because you are attempting to parse a date in the format ddMMyyyy, when by default DateTime.ToString() will produce a format with both date and time in the current culture.
For myself in Australia that would be dd/MM/yyy hh:mm:ss p e.g. 11/10/2013 11:07:03 AM
You must realise is that the DateTime object actually stores a date as individual components (e.g. day, month, year) that only needs to be format when you output the value into whatever format you desire.
E.g.
DateTime now = DateTime.Now;
string formattedDate = now.ToString("ddMMyyyy", DateTimeFormatInfo.InvariantInfo);
For more information see the api doc:
http://msdn.microsoft.com/en-us/library/8tfzyc64.aspx
For ParseExact to work, the string coming in must match exactly the pattern matching. In the other question you mentioned, the text was coming from a web form where the format was specified to be exactly one format.
In your case you generated the date using DateTime.Now.ToString() which will not be in the format ddMMyyyy. If you want to make the date round trip, you need to specify the format both places:
DateTime now = DateTime.Now;
DateTime dt = DateTime.ParseExact(now.ToString("ddMMyyyy"), #"ddMMyyyy", CultureInfo.InvariantCulture);
Debug your code and look at what the result of now.ToString() is, it's is not in the format of "ddMMyyyy", which is why the parse is failing. If you want to output now as a string in the ddMMyyy format, then try now.ToSTring("ddMMyyyy") instead.
now.ToString() does not return a string formatted in that way. Try using now.ToString("ddMMyyyy").
You might be better off testing with a static string like "30041999"

C# Asp.net Convert.toDateTime(datevalue) gives error with different cultureinfo need datepattern look like 5/1/2012 12:00:00 AM

In my Asp.net Website i have two textboxes (txtstartdate, txtenddate) applied JQquery Datepicker which popups gives date in format ("05/24/2012"). Work fine for cultureInfo("en-US"), when i change to ("de") ie German its give error "System.FormatException: String was not recognized as a valid DateTime.".
In my code behind file i am writing this code
string sDate = txtstartdate.Text; // 05/01/2012 (debugging gives this values)
string eDate = txtenddate.Text; // 05/24/2012 (debugging gives this values)
DateTime startdate = Convert.ToDateTime(sDate); // 5/1/2012 12:00:00 AM
DateTime enddate = Convert.ToDateTime(eDate); // 5/24/2012 12:00:00 AM
My requirement is datetime variable must give date of format 5/1/2012 12:00:00 AM whatever be the cultureinfo set doesnt matter to the date.So that i can execute select query in MsSql Server existing table having column datatype Datetime with data (5/1/2012 12:00:00 AM) formart
After Changing the CultureInfo (from Masterpage dropdownlist) Englsih to German gives error
Have tried this but not working
DateTime startdate = DateTime.ParseExact(sDate, "M/d/yyyy", null);
//tried also "MM/dd/yyyy"
Note: Set any cultileinfo, but the datetime pattern alwayz be 5/1/2012 12:00:00 AM ie en-US culture
You could try using "MM/dd/yyyy" as your format string when you call ParseExact, assuming that you're sure the input will always be in that format.
Alternatively, try using Convert.ToDateTime(yourString, CultureInfo.InvariantCulture) instead.
I think in this case you have to set the altFormat of your calendar to the format used by SQL server. Then, you can use a hidden field to store the altDate for each of your date pickers. When you submit, the value of the altField, in the correct format would be sent to your server instead of the culture-specific value that's displayed to the user.

Convert.DateTime

What Convert.DateTime will convert the date 7/25/2010 12:00:00 it's current format is(MM/dd/yyyy HH:mm:ss)?
When I convert this string format to date time I am getting the error "string was not recognized as valid DateTime"
None. Dates are not stored internally as a certain format.
If you want to parse a string into a date, use DateTime.ParseExact or DateTime.TryParseExact (the former will throw an exception if the conversion fails, the second uses an out parameter):
DateTime myDate = DateTime.ParseExact("7/25/2010 12:00:00",
"MM/dd/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
If you want to display a certain format, use ToString with the format string.
So, if you have a date object that represents midday of the 25th of July 2010 (doesn't matter how it is represented internally) and you want to format it with the format string "MM/dd/yyyy HH:mm:ss" you do the following:
string formattedDate = myDate.ToString("MM/dd/yyyy HH:mm:ss");
If you need to use Convert.DateTime, I'll assume you're working with a string you want to convert to a date. So you might try this:
DateTime date = Convert.DateTime("7/25/2010 12:00:00 am");
string formattedDateString = date.ToString("MM/dd/yyyy HH:mm:ss")
I'm making no assumptions as to why you'd want to do this, except that, well, you have your reasons.
DateTime.TryParse() or DateTime.Parse() will do the trick.
Edit: This is assuming that you are going from a string to a DateTime object.
Edit2: I just tested this with your input string, and I receive no error with DateTime.Parse

Categories