BKM
BKM

Reputation: 186

encountering String was not recognized as valid datetime using ParseExact

I want to insert the DateTime.Now as dd-MMM-yyyy format, but it is giving me string is not recognized as valid datetime while I use ParseExact.

db.AddInParameter(objdbCommand, "@dtAddedOn", DbType.DateTime, DateTime.ParseExact(Convert.ToString(DateTime.Now), @"dd-MMM-yyyy", System.Globalization.CultureInfo.InvariantCulture));

I have also tried :

DateTime.ParseExact(Convert.ToString(DateTime.Now), @"dd-MMM-yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture));

but it is giving me the same error

Upvotes: 0

Views: 83

Answers (1)

Fildor
Fildor

Reputation: 16084

Since you are inserting a DateTime anyway, you do not need to Convert to string and parse back to DateTime.

db.AddInParameter(objdbCommand, "@dtAddedOn", DbType.DateTime, DateTime.Now);

will do the trick.

DateTime does not have a format. Format comes into play as soon as you need a textual representation of the value that the DateTime represents. I also wouldn't recommend to use Convert for this but one of DateTime.ToString overloads.

Edit:

If you do not want to include the Time part, i.e. insert the Date, only you can use DateTime.Now.Date (see Date Property) or even easier DateTime.Today. This will give you a DateTime object with Time components all set to zero.

Edit 2:

Mind that there are some inherent problems using DateTime, especially if your system is going to be used spanning different TimeZones. Going deeper into this would go beyond the scope of this answer, though. Just want to give you a heads-up.

You may want to checkout DateTimeOffset and related Articles like Choosing between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo

Upvotes: 4

Related Questions