Reputation: 5088
I am trying to convert a string to a DateTime type in c# when i get the current time string and convert it,
it works but it wont work on my string, although they are the same time format i have tried this what am i doing wrong?
DateTime ReqRealDate = new DateTime();
DateTime NowDateFormat = new DateTime();
UPR.ReqID = Request.QueryString["reqID"];
string DateOfRequest = Request["Date"];
userInfo.UserID = Convert.ToInt32(Request["userID"]);
Session["TempUser"] = userInfo;
string dateFormat = "M/d/yyyy hh:mm:ss tt";
string NowDate = DateTime.Now.ToString(dateFormat);
NowDateFormat = DateTime.ParseExact(NowDate, dateFormat, CultureInfo.InvariantCulture);
ReqRealDate = DateTime.ParseExact(DateOfRequest, dateFormat, CultureInfo.InvariantCulture);
DateOfRequest = "6/3/2018 3:53:56 PM" NowDate = "6/3/2018 03:58:58 PM"
Upvotes: 1
Views: 140
Reputation: 34152
Have look at time 3:53:56
which is not exactly as hh:mm:ss
.
You should consider adding more reliable format or may be a list:
string[] dateFormat = new string[] {
"MM/d/yyyy hh:mm:ss tt",
"M/dd/yyyy hh:mm:ss tt",
"MM/dd/yyyy hh:mm:ss tt",
"M/d/yyyy hh:mm:ss tt",
"MM/d/yyyy h:mm:ss tt",
"M/dd/yyyy h:mm:ss tt",
"MM/dd/yyyy h:mm:ss tt",
"M/d/yyyy h:mm:ss tt"};
NowDateFormat = DateTime.ParseExact(NowDate, dateFormat, CultureInfo.InvariantCulture);
Or make your date string to match a specific format, that a single string dateFormat can be enough.
Upvotes: 2