String was not recognized as a valid TimeSpan. C# and SQL Sserver - c#

I get an error
String was not recognized as a valid TimeSpan
I am coding in C# and can't seem to find out what the problem is. How to avoid this error and is time(7) datatype in my database.
Any insight would be very much appreciated.
This is my code where it's failing:
Classes.ClsBooking.BookingDataTable.InsertBooking(TimeSpan.Parse(string.Format(DateTime.Now.ToString(), "HH:mm")));

Use either:
string.Format(DateTime.Now, "HH:mm")
or, preferably
DateTime.Now.ToString("HH:mm")
With what you are currently doing, you're passing a string (that's already formatted the date in the "default" format) as a parameter to "string.Format()", and then you're trying to tell "string.Format()" to reformat that string as "HH:mm". That won't work, as the parameter will no longer be recognised as DateTime

you just want TimeSpan.Parse(DateTime.Now.ToString("HH:mm"));

Related

Parsing Date Time string produces unexpected results

I'm trying to convert a string which is in the correct format into a date of exactly the same format for a linq query to work against a SQL date.
I've tried several conversion methods but all have failed. The example below shows the issue:
var test = DateTime.ParseExact("2019-04-09 13:15:00", "yyyy-MM-dd HH:mm:ss", null);
produces
{09/04/2019 13:15:00}
I have no idea why the date comes out like this but I would like to come out like:
2019-04-09 13:15:00
I tried with culture info but no luck. Not sure why this happening?
You have a fundamental misunderstanding of how DateTime values work. They do not have any human-readable format. Rather, they are stored as a binary value that is not human readable. The format you're seeing is something provided as a convenience by your debugger.
If you need a different specific format for anything other than use in SQL*, you can call ToString() with the appropriate format string. Just remember when you do that you are no longer working with a DateTime value, but are back to using a string again, and the best practice is to wait as long as possible before going back to strings.
*For SQL, you should be using parameterized queries, where there is a placeholder in the query and your datetime value is assigned directly to the parameter value without converting to a string first.
You parse the date in the correct format, so that's fine. The DateTime-object contains the correct value, so you can use it for your database.
If you want to see it in your prefered format you also need to output it using the same format, otherwise the default format of your user account (or in case of a web request the preferred language of the calling browser) will be used for displaying it.
Console.WriteLine(test.ToString("yyyy-MM-dd HH:mm:ss"));
If you are using Visual Studio, you can execute this command in the "Immediate Window" while running the debugger:
test.ToString("yyyy-MM-dd HH:mm:ss")
In other windows the debugger will use the default output format like described above.

String was not recognized as a valid DateTime from SQLite file

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.

Formatting String Variables that contain numbers/dates for printing in C#

Maybe it's a n00b question but I've looked at the .net/C# MSDN Library and on this site and have yet to come to a clear answer... say I had For Ex:
(this is not exactly the problem, as I'm not creating the string but reading them out of a DB. But serves to illustrate what I'm working with...)
string dob = "01/02/1990";
dob.ToString("MM/dd/YY"); //however, I can't do this. compiler gives me an error...
likely because it is already a string? How then could I get the string into the format that I want using specifiers, when it's already a string?
I know I could convert it to something else (a DateTime for Ex) and convert back to string using the ToString()...but this seems counter productive... to me at least
I also have several other "kinds" of string variables I'm trying to display into specific formats whilst saving them to a Idictionary for printing into a pdf's fields.
For ex:
d["amount"] = prod.sales.StringAmount; //(here StringSmount holds say 50000 (gotten from a DB), which I want to display as "50,000")
However, I also can't do prod.sales.StringAmount.ToString("N", CultureInfo.CurrentUICulture); cuz it's already a string! Is there an easy way to do this
or need I mess with String Buffers or the StringBuilder class??
thanks!
You can do something like this:
DateTime dob = DateTime.Parse("01/02/1990");
and then
dob.ToString("MM/dd/YY");
will work.
Note that DateTime.Parse() has various options for the possible date-time formats to accept, and that there is also a TryParse() version that returns false if the string is not a valid date - instead than throwing an exception. There are also DateTime.ParseExact() and DateTime.TryParseExact() variations.
Use the same approach for other data types beside date-times: first convert the input string in the correct data type (integer, float etc) - using the various Parse() or TryParse() methods, and then format the result of this conversion.
ToString returns a value without modifying the original.
Instead of
dob.ToString("MM/dd/YY");
use
dob = dob.ToString("MM/dd/YY");
First parse the string into a DateTime instance (via the Parse() or TryParse() methods). On the DateTime Instance you can then call ToString(..).
Using the format provided above, you would need to convert back to DateTime to use the .ToString("MM/dd/YY") format. The reason why is ToString is used to convert an object/value to a string representation and the DateTime object is nice enough to accept a format.
If you want to Format what is already a string, then you should be using String.Format. Visit this link: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx. This link shows the standard numeric formatters.
You may also want to create your own string format. Look into IFormatProvider and ICustomFormatter: http://msdn.microsoft.com/en-us/library/system.icustomformatter.aspx.
I would recommend first parsing it into a number/DateTime and then using the string formatting variables. For an example of why this can be necessary, consider that your "01/02/1990" string is ambiguous between Jan 2 and Feb 1, unless you parse it using DateTime.ParseExact.
I'd recommend this over 'rolling your own' (e.g. with StringBuilder) so that you can use the built-in culture-sensitive string formatting abilities of .NET.

Convert DateTime to string with format YYYYMMDD

I have birth dates stored as datetime in SQL Server 2008 like so:
2010-04-25 00:00:00.000
What is the best way, using C#, to convert and format this into a string with a YYYYMMDD format?
In the end, all I need is a string like:
20100425
Any help is greatly appreciated!
date.ToString("yyyyMMdd");
Should be what you need.
You need to get that value into a DateTime object and then you can use it's ToString() function like so:
.ToString("yyyyMMdd");
Are you able to get the data out of the database as a DateTime (.NET) object? If so, you can use the DateTime's instancename.ToString("yyyyMMdd")
If you haven't gotten to that stage yet, there's quite a few different ways to get the data out. It's a whole Google search in itself...
You just format the date using a custom format string:
string formatted = theDate.ToString("yyyyMMdd");
Note that the date doens't have a format at all when it's stored as a datetime in the database. It's just a point in time, it doesn't have a specific text representation until it's specifically created from the date.
Use the .ToString() method on the date time object, and pass in the format you want.

Problem during parsing datetime

I have problem when im trying parse datetime in format like: "1.00:29:00" 1- days,29-minutes, after invoke DateTime.Parse im getting "String was not recognized as a valid DateTime"
thanks in advance for any suggestion.
That's not a valid native datetime string format - see the remarks section here for more info - but that sounds a lot like you're really talking about a TimeSpan.
You can use ParseExact providing the format to use along with the value to parse.

Categories