Error Message as "String was not recognized as a valid DateTime." - c#

My Code:
DateTime? birthDate = DateTime.Parse(filterDictionary.ContainsKey("DOB") ? filterDictionary["DOB"] : string.Empty);
I am getting Error Message as "String was not recognized as a valid DateTime." How to solve this issue. Thanks.

The problem (at least one of them) is that you can't parse an empty string to a DateTime.
Change your line of code to this to move the parsing only when you find the key, and return null instead of parsing when you don't have it:
DateTime? birthDate = filterDictionary.ContainsKey("DOB") ? DateTime.Parse( filterDictionary["DOB"]) : (DateTime?) null;
The other problem might be that your dictionary DOB value is actually not possible to convert to a DateTime. If the above code does not work, please edit your question and post the value in filterDictionary["DOB"] when you get this error.

Well DateTime.Parse is always going to fail when you present it with an empty string.
It's not clear whether the time that you've seen this has been one where there has been data in the dictionary but it's invalid, or whether there's been no data and it's parsing string.Empty. Also note that DateTime.Parse returns DateTime, not DateTime?. If you want the value to be null if the entry wasn't in the dictionary, I'd actually use:
DateTime? birthDate = null;
string dobText;
if (filterDictionary.TryGetValue("DOB", out dobText))
{
birthDate = DateTime.Parse(dobText);
}
Or perhaps:
string dobText;
DateTime? birthDay = filterDictionary.TryGetValue("DOB", out dobText)
? DateTime.Parse(dobText) : (DateTime?) null;
Note that you need to cast at least one of the second or third operands to null here so the compiler can work out the type of the conditional expression.
You should also consider whether a plain call to DateTime.Parse is appropriate:
If you know the specific format you're expecting, call DateTime.ParseExact
If this is user input, you should probably be using TryParse or TryParseExact
If it's not user input, you should probably be specifying a parsing culture of CultureInfo.InvariantCulture
If it's direct user input in a GUI, is there a way you can avoid getting it as text in the first place?

Related

Convert to datetime from Oracle

i know there are a lot of similar questions, but I couldn't find what I was looking for.
Here is my oracle date:
string testdate= "2014-01-07 15:00:00.0000000";
And here is how I tried to convert to datetime:
DateTime.ParseExact(testdate, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture)
This throws a format exception. Any ideas?
My quick test also throws the string not valid datetime exception. Quick test:
Console.WriteLine(DateTime.ParseExact(testdate, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture).ToShortDateString());
I'd start by trying to avoid getting it as a string in the first place. Make sure you're using the appropriate data type in Oracle, and you should be able to call GetDateTime on the appropriate DataReader (or whatever you're using).
If you must parse it as text, then you need to specify a format which matches the value - so use 7 fs instead of 3, given that your value has ".0000000" at the end.
DateTime.ParseExact(testdate, "yyyy-MM-dd HH:mm:ss.fffffff",
CultureInfo.InvariantCulture)
But again, I'd strongly urge you to avoid having to deal with the value as text at all.
Why use ParseExact at all? Reqular Parse seems to work.
var dt = DateTime.Parse("2014-01-07 15:00:00.0000000", CultureInfo.InvariantCulture);
// Prints out 2014-01-07T15:00:00.0000000
Console.WriteLine(dt.ToString("o"));

How do you handle NULLs in a Date field through your C# code?

I am currently setting the date field to a Datetime.Now which is being done through the SQL query on the database.
I do a
SELECT NVL(mydatefield, sysdate) FROM myView;
This is not the most elegant approach I can think of. The better practice would be to check for a NULL.
I found that the DateTime class does not support the syntax that I am using for int values.
What approaches have you seen being used? What's your preference? How can you make a DateTime handle null values?
I don't want the DateTime.ParseExact in my front-end code to throw an exception.
DateTime? is a nullable DateTime. You could also use default(DateTime) to find non-set DateTime fields. A final option is to use DateTime.Min or DateTime.Max as a special value.
Instead of DateTime.ParseExact you can use DateTime.TryParse.
string input = "2010-10-04";
DateTime result;
bool success = DateTime.TryParse(input, out result);

C# String to DateTime

DateTime frm_datestart = DateTime.Parse(dateStart.Text);
This line throws the error:
Exception Details:
System.FormatException: String was not
recognized as a valid DateTime.
Where the entered string is from Jquery-UI, examples:
09/29/2010
09/30/2010
Anyone know what the correct format should be? I'm suprised this isn't working :S
You can use an overloaded version of the DateTime.Parse() method which accepts a second DateTimeFormatInfo parameter.
System.Globalization.DateTimeFormatInfo dti = new System.Globalization.DateTimeFormatInfo();
dti.ShortDatePattern = "MM/dd/yyyy";
DateTime dt = DateTime.Parse(dateStart.Text, dti);
look for DateTime.ParseExact method.
val = dateStart.Text.ToString("yyyy-M-d HH:mm:ss");
Use DateTime.ParseExact to specify format like this: DateTime.Parse("dd/MM/yyyy", dateStart.Text, null)
The problem with DateTime.ParseExact() method suggested in previous answers is, it fails on some Cultures. So your application may fail to run correctly on certain Operating Systems.
If you are sure that dateStart.Text will always be in the same format (i.e. en-US), you may try passing appropriate CultureInfo as a second argument. For format "MM/dd/yyyy" use CultureInfo.InvariantCulture.

date from string help. I can convert to the string I want, but I can't convert back

I have a string I need to convert back to a date. I can call .ToString("yyyyMMdd") and get the string i want. My question is how can I convert that back into a date? I'm trying something like the following with no luck.
DateTime d;
var formatInfo = new DateTimeFormatInfo {ShortDatePattern = "yyyyMMdd"};
if (DateTime.TryParse(details.DetectionTime.Date, formatInfo, DateTimeStyles.None, out d))
{
lit.Text = d.ToShortTimeString(); //would like 07/30/2010 as the text
}
I've never used DateTimeFormatInfo before if that isn't obvious. Can someone point me in the right direction. I know I could probably use substring and create a new DateTime(y, m, d) etc... I'm just wondering since c# interpreted .ToString() correctly, if it can't derive a date from the very same string it output.
The reverse of DateTime.ToString("yyyyMMdd") is DateTime.TryParseExact, passing "yyyyMMdd" as a format string.
IFormatProvider is a bit of a red herring. You'll normally pass either :
Thread.CurrentThread.Culture, if you're parsing a date typed by the user, when you should obey the user's date preferences
Or CultureInfo.InvariantCulture, if you're parsing a date provided by a program, when your behaviour shouldn't depend on the preferences the user has set up
Use d.ToString("MM/dd/yyyy")
For more options check out http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx
Edit: Read it wrong
Use DateTime.Parse() to parse the string to a datetime.
http://msdn.microsoft.com/en-us/library/1k1skd40.aspx
You can also use DateTime.TryParse to see if the string is able to convert to a date first.
http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx
Alternatively you can also use Convert.ToDateTime()
If you want the DateTime variable back after sending it to a string, save yourself the trouble and just cache or pass the actual DateTime variable around scopes to wherever you need it later and don't bother converting the text back into a DateTime class..
Sorry I just realized this doesn't answer your request, so what you're looking for is:
DateTime.ParseExact(someDateTime, "the format string you used to .tostring generating the string", null);
Convert.ToDateTime("07/30/2010");
I'm assuming you mean to convert a string to a DateTime format. If so use this:
DateTime yourStringConverted = Convert.ToDateTime( yourString );

Dateformat with nullable variable

I have this code:
startWeekDate = startWeekDate == null ? DateTimeHelpers.calcMondayDate(DateTime.Now) : DateTimeHelpers.calcMondayDate(startWeekDate.Value);
DateTime endWeekDate = startWeekDate.Value.AddDays(6);
startWeekDate is a parameter that is nullable. This works good, but I want to format it with: String.Format("{d:0}", .... ) but when I slap that around it I get error.
Cannot implicitly convert type 'string' to 'System.DateTime?
How shall I fix this problem?
/M
EDIT:
I'm trying to add this to the function instead, since it should always return dateformat without clock, but I get same error there with this code:
public static DateTime calcMondayDate(DateTime input)
{
int delta = DayOfWeek.Monday - input.DayOfWeek;
DateTime monday = String.Format("{d:0}", input.AddDays(delta));
return monday;
}
Cannot implicitly convert type 'string' to 'System.DateTime'
hmm, but input is DateTime, why does it complain about it being string?
You've shown the code that doesn't have a problem, but not the code that does have a problem. Please show the code which doesn't compile. It sounds like you're trying to assign a DateTime? variable a string value, e.g.
startWeekDate = string.Format(...);
That's definitely not going to work. What would you really want it to do with the formatted value once you've got it as a string? Use it where you want a string, not where you want a DateTime?.
One thing to add - your first line can be expressed more simply:
startWeekDate = DateTimeHelpers.calcMondayDate(startWeekDate ?? DateTime.Now);
EDIT: Now you've posted your code, it's clear why it's not working - as suspected, you're trying to assign a string value to a DateTime variable.
DateTime values don't have a format. They're like numbers - they have a value which isn't inherently formatted. It's like 0x10 and 16 are the same number, just written differently.
Now it sounds like you're just trying to return the date without the time - which is better done as:
return input.AddDays(delta).Date;
The Date property returns a DateTime with the same date, but midnight as the time.
On a side note, it's a shame that .NET has such a restricted set of date/time types, so that you can't really represent the idea of a time-less date. I'm trying to fix this situation, but it'll be a while before it bears fruit...
The error is "cannot convert string to DateTime".
Whch is exactly what this line is attempting to do:
DateTime monday = String.Format("{d:0}", input.AddDays(delta));
As I said in my comment above, you format at output time. Internally a datetime is just a number, it has no concept of format. You should simply return the input.AddDays(delta)
You get the compilation error because you have declared startWeekDate as a DateTime, but string.Format returns a string. One possible remedy is to change the declaration:
string endWeekDate = string.Format("{d:0}", startWeekDate.Value.AddDays(6));
However, now endWeekDate is a string, so you migh want to change the code a bit to keep it as is, and then introduce a new variable which is the string representation of that variable. Whether or not that is a good idea depends on the context.

Categories