User475983607 posted
venkatzeus
Hi.
I have data in a excel file, which contains string of the below format.
20170918
01/12/2019 ( 12 is the month )
I want to check if these are all valid dates ? I have tried the below code
if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,
DateTimeStyles.None, out dateTime))
How to pass the above formats ?
Thanks
The format string is "yyyyMMdd" and "dd/MM/yyyy". The standard documentation cover DateTime formats.
https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings
Two validation edits are required. One edit for each format. Keep in mind, this exact scenario was openly and clearly discussed in another one of your threads. If I recall, you are converting a VB .NET to C# and the VB code has this
check. Why did you remove the edit if the edit is needed?
static void Main(string[] args)
{
string[] dates = { "20170918", "01/12/2019", "12/30/2020" };
DateTime dateTime = DateTime.MinValue;
bool result = false;
foreach (string dateString in dates)
{
if (!DateTime.TryParseExact(dateString, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
result = DateTime.TryParseExact(dateString, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime);
}
else
{
result = true;
}
Console.WriteLine($"TryParseExact: {result}\t Value: {dateTime}");
}
}
Results
TryParseExact: True Value: 9/18/2017 12:00:00 AM
TryParseExact: True Value: 12/1/2019 12:00:00 AM
TryParseExact: False Value: 1/1/0001 12:00:00 AM