Reputation: 1237
I have Date that comes in Excel File. So far the requirement is, it can come in the Format as YYYY-MM-DD.
So I wrote the following code to convert it into MM/dd/yyyy:
DateTime excelDate = DateTime.ParseExact(value,
"yyyy-MM-dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None);
value = value != "" ? excelDate.ToString("MM/dd/yyyy") : value;
But now the requirement is : it can come in any format as YYYY-MM-DD or MM/DD/YYYY or YYYYMMDD or MM-DD-YY. Wonderin ghow to deal with these in a short way and convert that into MM/DD/YYYY ?
Upvotes: 3
Views: 619
Reputation: 7183
If you don't know in advance exactly what formats might be coming in, DateTime.Parse()
will attempt to detect the incoming format for you:
DateTime excelDate = DateTime.Parse(value
CultureInfo.InvariantCulture);
Note that you can also pass a DateTimeStyles
parameter, but may not want or need to, depending on the behavior you want.
See http://msdn.microsoft.com/en-us/library/kc8s65zs.aspx for details.
Upvotes: 0
Reputation: 499132
There is an overload to ParseExact
that takes and array of format strings.
var formats = new string[] {"yyyy-MM-dd", "MM/dd/yyyy", "yyyyMMdd", "MM-dd-yy"};
DateTime excelDate = DateTime.ParseExact(value,
formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None);
Upvotes: 8