I am reading from a Excel Report file and must convert this string from a cell to DateTime.
The String cell is like this
Viernes, 11 de noviembre de 2022
And the date will be different based on the day was created, the excel report is created in spanish but using english date for translation purpose.
Original | Translated |
---|---|
Lunes, 5 de agosto de 2023 | Monday, 5 of august of 2023 |
Miercoles, 7 de Marzo de 2023 | Wednesday, 7 of March of 2023 |
I used TryParse or TryParseExact but it detects as an invalid format even using cultureInfo = "es-PY" that correspondant culture of the generated excel report.
CodePudding user response:
You can escape the of
(de
) strings and use the correct format specifiers for each part:
string dateString = "Tuesday, 7 of March of 2023";
string format = @"dddd, d \o\f MMMM \o\f yyyy";
var date = DateTime.ParseExact(dateString, format, CultureInfo.CreateSpecificCulture("en-US"));
Console.WriteLine(date);
or the spanish version:
string dateString = "Martes, 7 de Marzo de 2023";
string format = @"dddd, d \d\e MMMM \d\e yyyy";
var date = DateTime.ParseExact(dateString, format, CultureInfo.CreateSpecificCulture("es-MX"));
Note that March 7, 2023 is a Tuesday, not a Wednesday, so the parsing of your example would fail because it's the wrong day of the week.
CodePudding user response:
This works fine for me
string s = "Viernes, 18 de noviembre de 2022";
var es = CultureInfo.GetCultureInfo("es");
if (DateTime.TryParse(s, es, out DateTime date)) {
Console.WriteLine(date);
} else {
Console.WriteLine("parse error");
}
Obviously, the word "de" is recognized as valid part of a Spanish date.
Note that the weekday name must match with the date. Otherwise you get a parse error.