I am working on a C# application. I have below code to validate the date:
private DateTime? ParseUserInputDate(string providedDate)
{
DateTime validDate;
var dateFormatIsValid = DateTime.TryParseExact(
providedDate,
Constants.DateFormats.UserInput,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out validDate);
return dateFormatIsValid ? validDate : (DateTime?)null;
}
When I pass "2/09/2019 12:00:00 AM" as providedDate
and UserInput format is "d/M/yyyy", it returns always false. Can someone help me to figure out this issue?
If you want to parse time , you have to mention time part in the pattern; if you have to use several patterns (say, with and without date) you can put them into one TryParseExact
:
private DateTime? ParseUserInputDate(string providedDate) {
// we can simplify the code with a help of out var
return DateTime.TryParseExact(providedDate,
new string[] {
"d/M/yyyy", // Try date first
"d/M/yyyy h:m:s tt", // if fails try date and time
},
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out var validDate)
? validDate
: (DateTime?) null;
}
...
// Date and Time
Console.WriteLine(ParseUserInputDate("2/09/2019 12:00:00 AM")
.Value
.ToString("dd.MM.yyyy HH:mm:ss"));
// Date only
Console.WriteLine(ParseUserInputDate("2/09/2019")
.Value
.ToString("dd.MM.yyyy HH:mm:ss"));
Outcome:
02.09.2019 00:00:00
02.09.2019 00:00:00
The format and input are completely different. if you pass "2/09/2019 12:00:00 AM", then change the format to "d/M/yyyy h:mm:ss tt"
Private static DateTime? ParseUserInputDate(string providedDate)
{
DateTime validDate;
string[] formats = { "d/M/yyyy h:mm:ss tt", "d/M/yyyy" };
var dateFormatIsValid = DateTime.TryParseExact(
providedDate,
formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out validDate);
return dateFormatIsValid ? validDate : (DateTime?)null;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.