changing date format before insertion to database - c#

I'm uploading an excel file to a server and then inserting its rows and columns into a database. I'm doing it line by line but I have a problem with datetime. After inserting 146 rows of data I get an error which reads:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
The problem is its the date. In the excel files the dates are formatted dd/mm/yyyy but the the database is taking them as being mm/dd/yyyy so when the date does past the 12th I get the out-of-range errror. I dont want to change my excel files so is there an option I can change on the database (MS SQL-server) or do I have to use c# code which can convert them before they get inserted... Thanks...

If you know the format coming from Excel, you are best parsing the string to a DateTime in C# with a specific IFormatterProvider.
The problem here is there is no culture information on the string coming from Excel, so the conversion to a DateTime can only take into account the culture of the database - in this case a format that reverses the month and day. This will mean that dates outside the range (as in your case) or ambiguous dates will never parse correctly.
In C# code you are able to specify a culture that implements IFormatterProvider, en-GB has the date format of the Excel dates you specify. The example in the MSDN documentation shows how to do this. My example briefing shows how to convert a string with an en-GB date format into a DateTime that is culture agnostic:
var culture = CultureInfo.CreateSpecificCulture("en-GB");
var date = DateTime.Parse("13/12/2011", culture);
SQL has the same problem with culture. A string representation of any culture-sensitive data will always lose the current culture. When converting that data you need to specify the culture if it differs from the server.
You can do this in SQL and hard-code the format of the string you are trying to convert (103 represents en-GB date formats dd/mm/yyyy):
declare #datestring varchar(10) = '13/12/2011' --13th December
-- 103 is the format code for UK dates with full yyyy century.
select convert(date, #datestring, 103) --gives 2011-12-13
declare #datestring2 varchar(10) = '05/04/2011' --5th April, ambiguous date.
select convert(date, #datestring2, 103) --gives 2011-04-05
Convert / cast format codes.
It is also worth noting that this will also correctly convert ambiguous dates such as 05/04/2011, which would reverse the month/day if the culture wasn't known.
For example, if you tried to convert the UK 5th April 2011 into a US date without telling the parser what the format is, you will get 4th May 2011 as output - reversing the month and day.

You can do this before inserting with T-SQL :
set dateformat dmy
See http://msdn.microsoft.com/fr-fr/library/ms189491.aspx

You can do in database as well probably try to write a stored procedure that inserts your data to database using your excelsheet.
User below mentioned TSQL code in your SP and that will work.
CREATE PROCEDURE ABC
AS
-- Do some operation
SET DATEFORMAT ydm;
insert into #dates
select '2008-09-01','2008-09-01'
END

I think you have to do it in c#.
Try something like this:
String excelDate = ...
String[] dateParts = excelDate.Split('/');
String sqlDate = dateParts[1] + "/" + dateParts[0] + "/" + dateParts[2];
...

First parse your excel datetime to C# datetime object and format the datetime object as let's say
DateTime dt = DateTime.Parse(drExcel["dateofExcel"]);
drDB["DateTime"] = dt.ToString("s");
hopefully it will solve your problem

Related

Oracle TO_DATE() function

I am trying to insert date into an oracle database which is imported from an excel spreadsheet. At some rows of spreadsheet, the date is represented in 24 hour format and at some rows it is represented in AM/PM format.
I started converting the date string to oracle format by using TO_DATE function as
"TO_DATE(\'" + Timestamp + "\', 'MM/DD/YYYY HH:MI:SS AM', 'nls_date_language=american')"
The "Timestamp" here is a C# string variable which has date in string format.
I am getting exception when the timestamp variable is represented in 24 hour format. Is there any way that I can make my C# code accept both type of date formats and insert into oracle table as they are?
Here are two ways you can go:
C# (as suggested above)
DateTime.ParseExact has an overload that lets you pass multiple format strings. It will use the first one that works. DateTime.TryParseExact also has this overload. DateTime.Parse does not.
string[] formats = {"dd/MM/yyyy HH:mm:ss", "dd/MM/yyyy hh:mm:ss tt"};
DateTime Timestamp = DateTime.ParseExact(inputDate, formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
Oracle
Have Oracle check for AM or PM and adjust the format string accordingly. This is the raw Oracle; I'll leave the string building to you:
TO_DATE(val,
CASE WHEN REGEXP_LIKE(val, '(AM|PM)')
THEN 'MM/DD/YYYY HH:MI:SS AM'
ELSE 'MM/DD/YYYY HH24:MI:SS'
END)
Any code issues let me know. I'm not at a machine where I could test these snippets.

Convert date time string in dd/mm/yyyy to datetime format mm/dd/yyyy

There is an input from CSV file which is in dd/mm/yyyy format.
I have to pass these date values to the stored procedure.
I want to convert this to mm/dd/yyyy format before I bulkcopy it to the database table from the datatable in the c# code.
Should I do this in the code or in the stored procedure which I am sending it to?
Please advise.I have tried all possible combinations.
You could you use DateTime.ParseExact,
var parsedDate = DateTime.ParseExact(dateString, "dd/MM/YYYY", CultureInfo.InvariantCulture);
where dateString is the string representation of the date you want to parse.
If your stored procedures expects a DateTime you could use the parseDate value. Otherwise, if it expects a string in the format you mentioned, you can pass the following value:
parsedDate.ToString("MM/dd/YYYY")
You should parse your value to DateTime in C# and pass this date value to your SQL client or ORM without converting it to a string
If your SQL column type is set to either one of the date value types it is quite impossible to format the date according to your desire, since the database engine does not store the formatted value but the date value itself.
Make sure to parse the DateTime in-code before updating its value in the SQL database.
string date = "2000-02-02";
DateTime time = DateTime.Parse(date); // Will throw an exception if the date is invalid.
There's also the TryParse method available for you. It will make sure the date value you're trying to parse is indeed in the right format.
string input = "2000-02-02";
DateTime dateTime;
if (DateTime.TryParse(input, out dateTime))
{
Console.WriteLine(dateTime);
}
After the storage you're more than welcome to select your preferred display format for your DateTime variable using one of the given formats (read link below for a full list of available formats).
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

What is the correct DateTime format for MySQL Database?

I am Inserting this DateTime data '12/21/2012 1:13:58 PM' into my MySQL Database using this SQL string:
String Query = "INSERT INTO `restaurantdb`.`stocksdb`
(`stock_ID`,`stock_dateUpdated`)
VALUES ('#stockID' '#dateUpdated');
and I receive this error message:
Incorrect datetime value: '12/21/2012 1:13:58 PM' for column 'stock_dateUpdated' at row 1
So what is the right format/value for dateTime to input into a MySQL database?
Q: What is the right format/value for DATETIME literal within a MySQL statement?
A: In MySQL, the standard format for a DATETIME literal is:
'YYYY-MM-DD HH:MI:SS'
with the time component as a 24 hour clock (i.e., the hours digits provided as a value between 00 and 23).
MySQL provides a builtin function STR_TO_DATE which can convert strings in various formats to DATE or DATETIME datatypes.
So, as an alternative, you can also specify the value of a DATETIME with a call to that function, like this:
STR_TO_DATE('12/21/2012 1:13:58 PM','%m/%d/%Y %h:%i:%s %p')
So, you could have MySQL do the conversion for you in the INSERT statement, if your VALUES list looked like this:
... VALUES ('#stockID', STR_TO_DATE('#dateUpdated','%m/%d/%Y %h:%i:%s %p');
(I notice you have a required comma missing between the two literals in your VALUES list.)
MySQL does allow some latitude in the delimiters between the parts of the DATETIME literal, so they are not strictly required.
MySQL 5.5 Reference Manual.
What I've used that works is year-month-day, with 24 hour time. In PHP it's date('Y-m-d H:i:s'), which I believe would correspond to yyyy-MM-dd HH:mm:ss in C#/.NET. (The time part is optional, and so are the dashes.)
Confirmed in the docs, Date and Time Literals:
Date and time values can be represented in several formats, such as quoted strings or as numbers, depending on the exact type of the value and other factors. For example, in contexts where MySQL expects a date, it interprets any of '2015-07-21', '20150721', and 20150721 as a date.
As mentioned in the comment, you are missing the delimiter , in the values. Also better to use STR_TO_DATE to convert string into date object first before inserting as:
String Query = "INSERT INTO `restaurantdb`.`stocksdb` "+
" (`stock_ID`,`stock_dateUpdated`) VALUES "+
"('#stockID', STR_TO_DATE(#dateUpdated, '%m/%d/%Y %h:%i:%s %p'))";
The MySql DATETIME format is YYYY-MM-DD HH:MM:SS - See this page

How to get date in C#, without localisation

My C# application have to read some date from MySQL database. Problem I have is that format of date depends on system localisation settings.
My question is if is possible that I always get date in formats yyyy-MM-dd hh:mm:ss, and yyyy-MM-dd, no matter of localisation settings.
Thank you in advance!
If you are storing the dates as true date or datetime values, your application will get the raw binary data back, and it will not be subject to localization until you create a string representation of the date values. My guess is that you are looking at the values in the debugger or using Console.WriteLine(theValue);, which will use the current locale. Always include the desired format and/or the desired culture when converting non-string values to strings.
If you are storing the dates as strings, you will always have to know exactly what format went into the database.
Assuming the dates are stored as date or datetime: just handle the values as they are, and don't convert them to strings until you need to show them to a user:
DateTime theValue = theReader.GetDateTime(fieldOrdinal);
var theValueAsText = theValue.ToString(CultureInfo.InvariantCulture);
var specificTextRepr = theValue.ToString("yyyy-MM-dd HH:mm:ss");
The theValueAsText variable will be a string representation that is not tied to a specific culture. The specificTextRepr will be your specific text representation.
You shouldn't be reading it back as a string from the database - you haven't shown how you're reading the data, but if you use something to populate a DataTable, or LINQ, or IDataReader.GetDateTime then there's no string formatting involved (assuming it's stored properly in the database, which it looks like it is).
A DateTime value doesn't intrinsically have a format, any more than an int is in decimal or hex - it's how you choose to convert it that matters, and you should almost always avoid doing that formatting unless you really need to.
Since you store the dates in date and date/time specific representations, formatting does not play into it at all (as opposed to some highly discouraged storage schemes when date/time is stored as strings, when formatting does matter, but for a wrong reason).
When you query MySQL from your C# code, you will get the correct dates no matter what your locale is. They will be displayed differently based on the locale, but they will represent the proper date regardless of the locale settings.
You can format the date directly in the query by using
date_format(dob,'%d/%m/%Y')
select date_format(dob,'%d/%m/%Y') dob from student where Id=1
Change
CurrentDate = DateTime.Now.ToString("MMM d, yyyy");
CurrentTime = DateTime.Now.ToString("hh:mm tt");
TO
CurrentDate = DateTime.Now.ToString("MMM d, yyyy",CultureInfo.InvariantCulture);
CurrentTime = DateTime.Now.ToString("hh:mm tt", CultureInfo.InvariantCulture);

SqlDatareader GetValue returning date value acording to system date format

Hi i am reading a value from a table using SqlDatareader, problem is it is always formatting the value acording to the machine date format settings.
for example the original date format in the source table is saved as
yyyy/mm/dd
when i use SqlDatareader.GetValue in a machine that has date set as MM/dd/YY
it is atutomatically converted to that format
is there anyway to retrive the date value with the original date formatting intact?
thanks
There is no "original date formatting", dates are kept internally as numbers, not strings.
Within a SQL query, you can choose the output formatting with
CONVERT(varchar(30), theColumn, nnn)
where "nnn" is one of the common date formats listed here: MSDN.
Personally I find that page confusing, so another (more useful) page is here: SQL Server Helper. From that page:
CONVERT(VARCHAR(20), GETDATE(), 100)
will return 'Jan 1 2005 1:29PM'
Probably not what you're looking for. But if you want to store the formatted date time, may be you should rather use VARCHAR or CHAR(N) as the field type. I would think the DATETIME field is to store datetime and the format it self isn't that important (or what it is meant for). However, you could reconvert it back to that format in C#.

Categories