Particular DateTime exception - c#

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.

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

Convert string to mm/dd/yyyy datetime

I'm trying to convert string which comes from textbox, for example in this format '03/24/2014' to DateTime. This is what I'm trying:
CultureInfo us = new CultureInfo("en-US");
dtAssemblyDate = DateTime.ParseExact(txtOperationSignatureDate.Value, "dd/MM/yyyy", us);
or
dtAssemblyDate = DateTime.ParseExact(txtOperationSignatureDate.Value, "dd/MM/yyyy", null);
But no luck and I'm getting exceptions that the value cannot be casted as DateTime. How can I fix this problem?
03/24/2014 isn't a valid date in dd/MM/yyyy format (there are only 12 months in a year1).
Either change your format string to MM/dd/yyyy or use a valid date in your chosen format.
1: Or 13 months in some types of Calendar, but "en-US" uses the 12-month Gregorian calendar.
DateTime myDate = DateTime.ParseExact("24/03/2014", "dd/MM/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
03/24/2014 has the day of the month as the middle component. That might seem strange, but that's how it's done in some parts of the world (mostly Northern America).
Thus, when specifying the format for parsing, you also have to put the day of the month (dd) in the middle:
CultureInfo us = new CultureInfo("en-US");
dtAssemblyDate = DateTime.ParseExact(txtOperationSignatureDate.Value, "MM/dd/yyyy", us);
Obviously, it is not possible to parse a text field that accepts both middle-endian (MM/dd/yyyy) and small-endian (dd/MM/yyyy) dates, because ambiguities like 01/02/2014 cannot be resolved automatically.
If the string is expressed in the format MM/dd/yyyy then
CultureInfo us = new CultureInfo("en-US");
dtAssemblyDate = DateTime.ParseExact(txtOperationSignatureDate.Value, "MM/dd/yyyy", us);
but I prefer to use DateTime.TryParse to avoid surprises...
if(DateTime.TryParse(txtOperationSignatureDate.Value,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dtAssemblyDate))
Console.WriteLine(dtAssemblyDate.ToShortDateString());
CultureInfo us = new CultureInfo("en-US");
DateTime dt = Convert.ToDateTime(txtOperationSignatureDate.Value, us.DateTimeFormat);
Whatever DateTimeFormat you require, you just need to pass corresponding culture with it.
Try using
string date = textbox.Value;
DateTime dt = Convert.ToDateTime(date);

Convert to dateTime from string (arabic culture to english)

string strHijdt ="29-02-1435";
DateTime hdt = DateTime.ParseExact(strHijdt, "dd/MMM/yyyy HH:MI24",
CultureInfo.InvariantCulture);
Getting error while convert to string("29-02-1435") to datetime
2/1435 has 28 days only
so, below will work
string aa="28-02-1435";
DateTime hdt = DateTime.ParseExact(aa, "dd-MM-yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(hdt.ToLongDateString());
DEMO
since you have given input as 29-02-1435 even you provide correct date time format (dd-MM-yyyy) you will get error for the invalid date
Two problems here:
1. As mentioned above, expected format for does not match string (there is no time, different separator)
2. If your date string is in Hijri calendar, you should either provide correct culture explicitly or use system culture (pass null for IFormatProvider):
string strHijdt = "29-02-1435";
var culture = CultureInfo.GetCultureInfo("ar-SA");
DateTime hdt = DateTime.ParseExact(strHijdt, "dd-MM-yyyy", culture);

String was not recognized as a valid DateTime when parse exact

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)
{
///
}

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