String was not recognized as a valid DateTime when parse exact - c#

I get the following exception when converting to DateTime:
String was not recognized as a valid DateTime.
lbl_RequestDate.Text = "13/2/2013";
CultureInfo provider = CultureInfo.CurrentCulture;
string[] format = provider.DateTimeFormat.GetAllDateTimePatterns();
Follow.RequestDate = DateTime.ParseExact(lbl_RequestDate.Text, format, provider, DateTimeStyles.None);

You can use thje format d/M/yyyy, Notice the single M used for the month.
Follow.RequestDate = DateTime.ParseExact(lbl_RequestDate.Text, "d/M/yyyy", provider, DateTimeStyles.None);
The method: provider.DateTimeFormat.GetAllDateTimePatterns() returns almost 155 formats, but none of them (from your current culture seems to) supports format d/M/yyyy that is why you are getting the exception. If your date has Month as 13/02/2013 then the formats returned by the method would work since the closest format is dd/MM/yyyy in the formats array.

Maybe this will help :
DateTime.ParseExact("13/2/2013","d/M/yyyy",CultureInfo.GetCultureInfo("en-US"), DateTimeStyles.None );
notice :
d is for Day (01 is also acceptable)
M is for Month (11 is also acceptable)

Try it like this:
Follow.RequestDate = DateTime.ParseExact(lbl_RequestDate.Text, "d/M/yyyy", CultureInfo.InvariantCulture);

DateTimeFormatInfo.GetAllDateTimePatterns() method returns on my machine (tr-TR Culture) 29 format but none of these support d/M/yyyy date format, that's why you are getting FormatException.
But in my culture DateSeparator is . so I can't exactly solve this problem using CultureInfo.CurrentCulture but when I use Egypt cultureinfo (it's wrote on your profile) CultureInfo.GetCultureInfo("ar-EG") this code works without any error;
CultureInfo provider = CultureInfo.GetCultureInfo("ar-EG");
string[] format = provider.DateTimeFormat.GetAllDateTimePatterns();
DateTime d = DateTime.ParseExact("13/02/2013", format, provider, DateTimeStyles.None);
Unfortunatly your your all datetime pattern doesn't support d/M/yyyy format.
Unfortunatly, changing this string to 13/02/2013 doesn't solve this problem because as I said on before, my all formats (in tr-TR Culture) doesn't support dd/MM/yyyy format either.
My humble advice is here, list all your datetime patterns and check manually if your string is recognized format with this datetime pattern like;
string[] format = provider.DateTimeFormat.GetAllDateTimePatterns();
foreach (var f in format)
{
///
}

Related

Convert to DateTime from a string '10-April-2020'

Looking for assistance in converting a date string i receive from a web form, where the format will be something like "10-April-2020". I need to save this into the database in the US date format "yyyy-mm-dd" so that the example date provided would go in as '2020-04-10'.
This is what I have so far, which complains that it is not a valid datetime.
string LicenseExpiry = LicenseExpiry.Text;
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime dateExpires = DateTime.ParseExact(LicenseExpiry, "yyyy-MM-dd", culture);
I have also tried the following which also fails.
DateTime dateExpires;
string LicenseExpiry = LicenseExpiry.Text;
IFormatProvider culture = new CultureInfo("en-US", true);
if (DateTime.TryParseExact(LicenseExpiry, "yyyy-MM-dd", culture, DateTimeStyles.None, out dateExpires))
{
// Do something
}
Can anyone help with either of the attempts to see what went wrong? I am not allowed to change the Ui/Form to do any client side date manipulation either, and so my solution needs to be done in the C# code behind file.
MM means the month number (from 01 through 12)
To parse 10-April-2020, you
need MMMM, see
Custom date and time format strings
The "MMMM" custom format specifier represents the full name of the month

Dateformat is right but getting String was not recognized as a valid DateTime

My dateformat is dd/MM/yyyy.
I have a date column in my file with values like 1/08/2019 to 31/08/2019.
But I'm getting the following error when processing that file:
System.FormatException: String was not recognized as a valid DateTime.
at System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style)
You've specified in your format string that the days and months must be double digits, but it appears that your input can be single digits.
In order to solve this, you need to specify a single digit in the format string by using a single d for the day portion (and a single M for the month, too).
It's also safe to use a single digit in the format string, since it will handle both single and double digits.
So your format string should look like: "d/M/yyyy"
For example, these all work:
var a = DateTime.ParseExact("1/8/2019", "d/M/yyyy", CultureInfo.CurrentCulture);
var b = DateTime.ParseExact("1/08/2019", "d/M/yyyy", CultureInfo.CurrentCulture);
var c = DateTime.ParseExact("01/8/2019", "d/M/yyyy", CultureInfo.CurrentCulture);
var d = DateTime.ParseExact("01/08/2019", "d/M/yyyy", CultureInfo.CurrentCulture);
difficult to say as you show the error but not the actual code, as you have dates in your file of differennt format, like d/MM/yyyy and dd/MM/yyyy try to use TryParse instead of ParseExact and if the TryParse fails with one format ( d/MM/yyyy ), then do another TryParse with the second format ( dd/MM/yyyy ) that way you should be able to cover both cases.
Again, without seeing the code it is difficult to give more detailed feedback.
also you could use an approach with TryParseExact and multiple format strings, like shown here:
var formatStrings = new string[] { "MM/dd/yyyy hh:mm:ss tt", "yyyy-MM-dd hh:mm:ss" };
if (DateTime.TryParseExact(dt, formatStrings, enUS, DateTimeStyles.None, out dateValue))
return dateValue;
see this SO answer: https://stackoverflow.com/a/17859959/559144

Particular DateTime exception

I need to convert to DateTime some strings with this format "MMM-yy". I'm working with the culture "{es-ES}".
It works fine with all month except with March (In spanish Marzo).
This throws me this exception:
'Convert.ToDateTime("Mar-13")' threw an exception of type
'System.FormatException' System.DateTime {System.FormatException}
I've tried:
string format = "yyyyMM";
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
result = DateTime.ParseExact("Mar-13", format, provider);
and this:
DateTime date = Convert.ToDateTime("Mar-13");
This works fine for example with:
"Jun-13"
"Feb-13"
"Nov-13"
...
EDIT
The real problem is with:
DateTime date = Convert.ToDateTime("Ene-13"); -> ok
DateTime date = Convert.ToDateTime("Feb-13"); -> ok
DateTime date = Convert.ToDateTime("Mar-13"); -> crash
DateTime date = Convert.ToDateTime("Abr-13"); -> ok
....
Your date string "Mar-13" doesn't match your format "yyyyMM". Your format should be MMM-yy.
You should see: Custom Date and Time Format Strings
In your format
"MMM" - The abbreviated name of the month.
"yy" - The year, from 00 to 99.
EDIT:
For your question why Convert.ToDateTime("Mar-13"); is failing. You need to look at the following lines of code:
var currentCulture = new CultureInfo("es-ES");
var monthNames = currentCulture.DateTimeFormat.AbbreviatedMonthNames;
var dayOfWeeks = currentCulture.DateTimeFormat.AbbreviatedDayNames;
If you watch the returned values in debugger, You will see that for the culture es-ES there is a match between Month Name and Day name and that is on mar.
Marzo/March as Month
Martes/Tuesday as day
Both of these uses the same abbreviation i.e. Mar. Since Convert.ToDateTime would try to use possible formats for the string it fails to recognize Mar as Month or Day Name. That is why you get exception.
It is always a good idea to use DateTime.ParseExact and specify a single or multiple possible formats.
Your format and value don't match. Try this instead:
string format = "MMM-yy";
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
result = DateTime.ParseExact("Mar-13", format, provider);
EDIT
For the es-ES format provider, my guess is that Mar is ambiguous between Marzo (March) and Martes (Tuesday). You should be fine if you use ParseExact with the proper format:
string format = "MMM-yy";
DateTime result;
CultureInfo provider = CultureInfo.GetCultureInfo("es-ES");
// fails
result = DateTime.Parse("Mar-13", provider);
// works
result = DateTime.ParseExact("Mar-13", format, provider);
result = DateTime.ParseExact("Abr-13", format, provider);
EDIT 2
This appears to be a known bug. Their workaround is to use a similar culture, however if your date format is known, I'd recommend using ParseExact to explicitly define the format rather than letting the framework try and infer the format.
Reference to my answer about logic behind automatic DateTime parsing: How Convert.ToDateTime() parses a given string when the given culture does not know the format
You can automatically parse Abr-13 in es-ES culture, because Abr can be matched only as MonthToken. But in case of Mar-13 - Mar can be matched as MonthToken and also it can be matched as DayOfWeekToken (Tuesday), so DateTime.Parse/Convert.ToDateTime methods are confused and throw exception.
If you execute the code from referenced answer against es-ES culture, you would see the following in the output:
mar DayOfWeekToken 2
Mar MonthToken 3
There are no multiple matches for full months names though, so you can safely parse 'marzo', 'abril' values.
Since DateTime.Parse/Convert.ToDateTime methods are confused by this duality of Mar value, we need to provide a hint to it using DateTime.ParseExact method:
DateTime output = DateTime.ParseExact("Mar-13", "MMM-yy", CultureInfo.GetCultureInfo("es-ES"));
I think you need to use the correct CultureInfo and fix the format string
CultureInfo provider = new CultureInfo("ES-es");
DateTime result = DateTime.ParseExact("Abr-13", "MMM-yy", provider);
You need to use the Spanish culture info in association with the "MMM-yy" format :
string format = "MMM-yy";
DateTime result;
CultureInfo provider = new CultureInfo("es-ES");
result = DateTime.ParseExact("mar-13", format, provider);
result = DateTime.ParseExact("abr-13", format, provider);
On my system the current culture is en-US the following code will fail when trying to convert abril (April):
string format = "MMM-yy";
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
result = DateTime.ParseExact("abr-13", format, provider);
Therefore on my system I have to create a Spanish culture for the code to work:
string format = "MMM-yy";
DateTime result;
CultureInfo provider = CultureInfo.CreateSpecificCulture("es-ES");
result = DateTime.ParseExact("abr-13", format, provider);
So you need to be aware what culture your code is running on and take the proper action.

Console application string was not recognised as valid datetime

I have a excel sheet in which am taking a date column in this format "23/8/11 01:33:01:PM"
and am inserting it in sql 2008 using datarow but am getting a error
String was not recognised as valid datetime.
Can any one please help?
DateTime newdate = Convert.ToDateTime(row[8].ToString());
Here how Convert.ToDateTime method looks like when you decompile it;
public static DateTime ToDateTime(string value)
{
if (value == null)
return new DateTime(0L);
else
return DateTime.Parse(value, (IFormatProvider) CultureInfo.CurrentCulture);
}
As you can see, this method use DateTime.Parse method with your CurrentCulture. And if your string doesn't match your current culture date format, your code will be broken. That's the reason you get this error.
Use DateTime.ParseExact with "dd/M/yy hh:mm:ss:tt" format instead.
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly or an exception is thrown.
string s = "23/8/11 01:33:01:PM";
DateTime newdate = DateTime.ParseExact(s, "dd/M/yy hh:mm:ss:tt", CultureInfo.InvariantCulture);
Console.WriteLine(newdate);
Output will be;
8/23/2011 1:33:01 PM
Here a DEMO.
For your case;
DateTime newdate = DateTime.ParseExact(row[8].ToString(), "dd/M/yy hh:mm:ss:tt", CultureInfo.InvariantCulture);
For more informations, take a look;
Custom Date and Time Format Strings
Convert.ToDateTime internally calls DateTime.Parse which by default will use the current culture of your application. If 23/8/11 01:33:01:PM is not a valid format for this culture then this method will fail.
For specific date formats it's best to use DateTime.ParseExact e.g.
DateTime.ParseExact("23/8/11 01:33:01:PM", "dd/M/yy hh:mm:ss:tt", CultureInfo.InvariantCulture);
This approach makes your code culture independent which means the date will always be parsed correctly (given it's in the specified format).
This will work:
DateTime newdate = Convert.ToDateTime("8/23/11 01:33:01 PM");
I changed day and month and removed the colon a the end. But that is very specific. You need to know more about the dates passed to do that.

Get DateTime Obj from "mm/yyyy" format Date string

I have a date string in format "08/1999" I want to get the first date of the corresponding month. eg : in this case 08/01/1999.
It is simple for en-Us culture. I break the string, append "01" in the string to get 08/01/1999 and then DateTime.Parse(datestring) but this is valid for en-US culture only.
How can I do this for different culture ?
My datestring will always be in mm/yyyy format. and I am trying to obtain a DataTime obj from this dateString.
Use ParseExact method. Note upper-cased M's are for months and lower-cased m's for minutes.
string dateToConvert = "08/1999";
string format = "MM/yyyy";
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result = DateTime.ParseExact(dateToConvert, format, provider);
Output:
{1999-08-01 00:00:00}
You can also use Convert.ToDateTime and Parse methods. It will produce the same result, but in implicite way:
DateTime result = Convert.ToDateTime(dateToConvert, provider); // Output: {1999-08-01 00:00:00}
DateTime result = DateTime.Parse(dateToConvert, provider); // Output: {1999-08-01 00:00:00}
Read more at:
Parsing Date and Time Strings
Standard Date and Time Format Strings
Custom Date and Time Format Strings
I'm not sure if I understand your question correctly, but you can try passing CultureInfo.InvariantCulture if you want to force the US date format regardless of the regional settings of the client computer:
DateTime.Parse("08/1999", System.Globalization.CultureInfo.InvariantCulture)
I break the string, append "01" in the string to get 08/01/1999 and then DateTime.Parse(datestring)
That's a very long-winded way to do it. Simply this will work:
DateTime.Parse("08/1999")
How can I do this for different culture ?
If your string is always in this format, do this:
DateTime.Parse("08/1999", CultureInfo.InvariantCulture)

Categories