In my C# app, I pass a string variable that is of format yyyymmdd-yyyymmdd that represents a from and to date. I want to get the start and end times for these dates respecti
That's pretty much what I would do, with some small tweaks (really no big deal, just nitpicking):
TryParse()/TryParseExact() methods should be used which return false instead of throwing exceptions.FormatException is more specific than ExceptionParseExact()/TryParseExact() will do this"00:00:00" and "23:59:59" are not neededtrue/false is you were able to parse, instead of throwing an exception (remember to check value returned from this method!)Code:
private bool ValidateDatePeriod(string pdr, out DateTime startDate,
out DateTime endDate)
{
string[] dates = pdr.Split('-');
if (dates.Length != 2)
{
return false;
}
// no need to check for Length == 8 because the following will do it anyway
// no need for "00:00:00" or "23:59:59" either, I prefer AddDays(1)
if(!DateTime.TryParseExact(dates[0], "yyyyMMdd", null, DateTimeStyles.None, out startDate))
return false;
if(!DateTime.TryParseExact(dates[1], "yyyyMMdd", null, DateTimeStyles.None, out endDate))
return false;
endDate = endDate.AddDays(1);
return true;
}