Reputation: 5670
I have simple one line code
var startYearString = DateTime.Parse("03/21/2014").Year;
I expect this to work, But it throws an error like this
System.FormatException was unhandled by user code
HResult=-2146233033
Message=String was not recognized as a valid DateTime.
Source=mscorlib
StackTrace:
at System.DateTime.Parse(String s)
at ConnectBLL.usercontrols.users.UserProfile.Page_Load(Object sender, EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:
I have no idea what went wrong?
Upvotes: 1
Views: 277
Reputation: 26209
You need to use DateTime.ParseExact()
if you already know the Date Format.
Try This:
var startYearString = DateTime.ParseExact("03/21/2014","MM/dd/yyyy",
CultureInfo.InvariantCulture).Year;
Explanation:
yyyy
- Year in 4 digits
MM
- Month in two digits
dd
- Date in two digits
hh
- Hours in two digits.
mm
- Minutes in two digits.
ss
- Seconds in two digits.
fff
- Milliseconds
tt
- AM or PM.
See this for more information : DateTime custom formats
Upvotes: 7
Reputation: 3444
Try
var provider = CultureInfo.InvariantCulture;
var dateString = "03/21/2014";
var format = "d";
var output = DateTime.ParseExact(dateString, format, provider);
Upvotes: 2
Reputation: 28107
Make sure your culture is set to the type you are parsing.
DateTime.Parse("01/23/2014", new CultureInfo("en-US")); // happy
DateTime.Parse("01/23/2014", new CultureInfo("en-GB")); // sad
DateTime.Parse("23/01/2014", new CultureInfo("en-GB")); // happy
Upvotes: 1