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.
Related
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
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);
I want to convert datetime.now format which is "dd/mm/yyyy hh:mm:ss AM/PM" to US time format i.e. "mm-dd-yyyy hh:mm:ss AM/PM". More over i want the converted format as datetime not in string because the same is being stored in the database and the field in the database is in datetime format so it will not take string.Please suggest....
A DateTime value doesn't have a format. DateTime.Now doesn't have a format, and if you do any kind of conversion, if you've got a DateTime, there's no format. The concept of a format only applies when you're converting to or from a string - and DateTime.Now is a DateTime, not a string.
Just insert the value into the database using DateTime.Now (or DateTime.UtcNow) and you'll preserve the data which is the important part.
You should only perform string conversions when you actually have to - at which point you can use DateTime.TryParseExact and DateTime.ToString using custom date/time format strings. (Use TryParseExact for user input; for machine input which really should be valid, use DateTime.ParseExact.)
Note that it's usually a good idea to use custom date/time patterns with the invariant culture, or standard date/time patterns with "real" cultures (e.g. the user's culture).
Try this. Standard Date and Time Format Strings
DateTime.Now.ToString("g",CultureInfo.CreateSpecificCulture("en-us"))
DateTime usDateTimeFormat = DateTime.Parse(DateTime.Now ,
System.Globalization.CultureInfo.GetCultureInfo("en-us"));
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
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