I have a program, that puts the .txt files to a database file (im using system.data.sqlite NuGET package). I have yyyy.MM.dd format set on my Pc, and it's used by the database too, however I still get the above mentioned error.
An additional info, that could help, is that when I set the table's appropriate column to a simple string it's working as normal, but as soon As I set it to date it gives me this exeption.
Can someone please help me?
You seem to be mixing up how a type is formatted into text with the type itself. If a column is typed as date, then its expecting a date, not a text conforming to whatever date format you have in mind.
Its the same is if you try to do the following:
DateTime date = "01.01.2020";
This won't compile, because string, nevermind if it represents a valid formatted date, and DateTime are two altogether different types.
If you are reading from a text file, you first need to convert the formatted string representations to their corresponding DateTime. See DateTime.TryParse method on how to do this. Once you have valid dates in your hands, try pushing those to the DB.
Related
I'm relatively new to C# and I'm still learning a lot. I also searched stackoverflow for similar problems but got to a point where I'm stuck.
In my VSTO Excel project I'd like to output dynamic data coming from a database with a predefined number format per column also coming from the database. The user can define his own layout of the report. Everything is working just fine, I have just problems formatting the date value.
When it's about to output a date column, the format should be automatically be determined by the program instead of predefining it in the database as well. The date value gets already inserted in the Excel sheet as the decimal number it should be. Everything okay here. When I manually format it in Excel itself, it is displayed correctly.
But I want to format the date with C# like it would be formatted when I do it manually by clicking on the short date format in Excel. And it should work in every country, regardless in which language the office package was installed.
I'm working with a German installation and I expect the format to be "TT.MM.JJJJ". When formatting the column with this fixed string, it works perfectly (at least in Germany I guess).
It makes no difference if formatting it with
CurrentWorksheet.Columns[queryColumn.Position].NumberFormat = "TT.MM.JJJJ";
or
CurrentWorksheet.Columns[queryColumn.Position].NumberFormatLocal = "TT.MM.JJJJ";
Both end up in the same (correct) result. That the first line is working as well is the first thing which was unexpected for me, but that's not the main point. I tried to format it dynamically by replacing "TT.MM.JJJJ" with the following lines:
// Leads to dd.MM.yyyy
System.Globalization.DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
// Fixed German culture still leads to dd.MM.yyyy
CultureInfo.CreateSpecificCulture("de-DE").DateTimeFormat.ShortDatePattern;
// MM/dd/yyyy - also not helpful
CultureInfo.InvariantCulture.DateTimeFormat.ShortDatePattern;
When using the first or second ShortDatePattern the date 27.08.2014 is shown as "dd.08.yyyy". Excel simply doesn't unterstand "dd" or "yyyy". I thought at least when using NumberFormat instead of NumberFormatLocal it would work, because it's the global format, but it doesn't. It feels like Microsoft has implemented the date formatting more complicated that it could be.
How would I determine the correct date pattern here?
The answer (it still is a kind of workaround) is pretty much found in another question:
How to set localized short-date format for a cell in Excel with C#?
There's just a very small difference I had to make in the method for constructing the ShortDatePattern (the Application parameter for DateFormatComponentCodes).
public static string ConstructExcelShortDatePattern()
{
var systemDateComponentCodes = new DateFormatComponentCodes();
var excelDateComponentCodes = new DateFormatComponentCodes(Globals.ThisAddIn.Application);
string systemShortDatePattern = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
string excelShortDatePattern = systemShortDatePattern.Replace(systemDateComponentCodes.Year, excelDateComponentCodes.Year).Replace(systemDateComponentCodes.Month, excelDateComponentCodes.Month).Replace(systemDateComponentCodes.Day, excelDateComponentCodes.Day);
return excelShortDatePattern;
}
Thanks to Heinzi for finding a great answer and Jordan for providing such a useful class!
I am having a problem with parsing excel content to datetime type.
In my country, there are just two cultureinfo to use: "vi-VN" (dd/MM/yyyy) and "us-US" (MM/dd/yyyy).
For some cases I test, both DateTime.Parse with cultureinfo above throwing error "String is not recognized as a valid datetime".
I want to use DateTime.ParseExact instead of above approach. In order to do this, I must get a string like "12/31/2018". But when I use Epplus, it reads the content of the cell as a number 43465. This way, I cannot parse use DateTime.ParseExact.
Any here know how to read the excel as you see on the screen ?
Thank you.
DateTime.FromOADate(Double) Method
var dateTime = DateTime.FromOADate(43465);
I'm new to MySQL and C#.
I stored certain values in a column with data type Date. I did not want the time, only the date to be stored.
On viewing these values using phpMyAdmin or MySql command line, I see them in the format:
YYYY-MM-DD
However, when I retrieve these values in to my web application, they are displayed in the following format:
YYYY-MM-DD HH:MM (the time is specifically 12:00).
Why does this happen? And how can I prevent this from happening?
when you store in C# your date field, you use DateTime object. In this object when you don't specify the time part will be put a default value depends on Globalization.
You can study how DateTime works here
You can convert the date to the format you like when you fetch the data, using date_format():
select date_format(datecol, '%Y-%m-%d')
This returns the value as a string.
You shouldn't retrieve the value as a string from mysql. Why? Because if you ever need to do any operations on that value, such as adding a day, then you will need to parse it back into a DateTime again. String parsing can be slow, and when it comes to dates they are prone to errors like misinterpretation of mm/dd/yyyy and dd/mm/yyyy formatting.
The problem you have is that .NET does not have just a Date type. It only has a DateTime type. So loading a MySQL DATE type, is going to get a DateTime with the time portion set to midnight.
There's no direct problem with that, except on how are outputting the result. If you just call .ToString() without any parameters, or you implicitly use it as a string, then you are going to get a result with the full date and time. You simply need to provide a parameter to indicate what formatting you want.
Without any parameters, you are getting the General "G" format. This is explained in the documentation here.
In other words:
yourDateTime.ToString() == yourDateTime.ToString("G")
You can read about all of the other formats available, here and here.
In particular, if you just want the date, then you probably want to do this:
yourDateTime.ToString("d")
Based on your comments, you should be doing this instead:
MySQL Query:
SELECT Gbstartdate FROM TblGbDef
C#:
DateTime gb_start_date = (DateTime) datareader[0];
my c# program selects a datetime field from database and returns the data like the following:
21/06/2012 4:11:48 p.m.
it is not stored this way though (it's stored like 2012/06/21 15:19:10:000).
my locale is set to English/New Zealand
but when I try to save it back to database
the ISDATE() sql function doesn't like that format and just returns NULL. Do I have any options to set the time format in sql or c#? What in sql or c# is making it put "p.m."? (instead of just "PM", which by the way works)
Summing up the problem
See latest related link
You shouldn't be saving it in the database as text at all - you should be using the relevant data type such as DATETIME, and passing DateTime values from .NET to the database using SQL parameters. If you're using the right data type, the value won't actually be stored as "2012/06/21 15:19:10:000" at all. That may be how you see it in SQL Server Studio or something similar, but that doesn't mean it's the raw storage format.
Logically, a date/time doesn't have a format any more than the number ten is "10" (decimal) vs "A" (hex). Avoid string conversions as far as you can, and your life will be easier.
Note: See Jon's response about properly saving the DateTime in the database rather than a string.
For C# String formatting:
The DateTime object can output in different formats using the .ToString() function.
Please see the following links
Custom Date and Time Format Strings
DateTime.ToString Method
So, for example:
DateTime.Now.ToString("dd/MM/yyyy h:mm:ss");
That will output in the format you have in your question.
I think your issue is related to the Set language setting in sql.
Similar to this question: SQL Server ISDATE() Function - Can someone explain this?
Can you try to set your sql language to match your format?
Most of the SQL datetime formats should be recognizable by C# DateTime.Parse(youSQLDatetimeVariable). I find it a bit odd what's happening in your case.
Like other said you really shouldn't but here is how you can convert DateTime to various formats:
SELECT Convert(VARCHAR, MyDateTimeField, 112) from MyTable
That number (112 ) indicates the DateTime format that will appear as Varchar
All formats can be found here in details:
http://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/
Or within your C# code with
YourDatetimeVariable.ToString("MM-dd-yyyy")
Or whatever format you want within those quotes where MM- month number, dd - day number, yyyy - year.
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#.