So I have a date String coming in with the short date of today. For Example "1-11-2017"
//Here i convert the HttpCookie to a String
string DateView = Convert.ToString(CurrDay.Value);
//Here i convert the String to DateTime
DateTime myDate = DateTime.ParseExact(DateView, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
After running the code I get the error:
FormatExeption was unhandled by user code
An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code
Additional information: String was not recognized as a valid DateTime.
Python has a built-in method to parse dates, strptime . This example takes the string “2020–01–01 14:00” and parses it to a datetime object. The documentation for strptime provides a great overview of all format-string options.
parse() The Date. parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the ISO 8601 format ( YYYY-MM-DDTHH:mm:ss.
A date and time format string defines the text representation of a DateTime or DateTimeOffset value that results from a formatting operation. It can also define the representation of a date and time value that is required in a parsing operation in order to successfully convert the string to a date and time.
1-11-2017
is not in the format of dd-MM-yyyy
, specifically the first part. Use d-M-yyyy
instead which will use one digit day and month when the value is below 10 (ie. no 0 padding).
Test:
DateTime myDate = DateTime.ParseExact("1-11-2017", "d-M-yyyy", System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(myDate.ToString());
If you do not know if there will be 0 padding you can pass an array of acceptable formats, the parser will try each one in order they appear in the array.
DateTime myDate = DateTime.ParseExact("1-11-2017", new string[]{"d-M-yyyy", "dd-MM-yyyy"}, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
Fiddle
The Date format dd
stands for The day of the month, from 01 through 31.
You either supply it as 01-11-2017
or change your formatter to d-MM-yyyy
.
Here's a reference to Custom Date and Time Format Strings
I solved this using yyyy-MM-dd instead of dd-MM-yyyy (and later converting it to normal dates) Becouse the var always was the day of today the day can be 1 and 2 digits
CurrDay.Value = DateTime.Now.ToString("yyyy-MM-dd" );
// Convert String to DateTime
dateFrom = DateTime.ParseExact(CurrDay.Value.ToString(), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
The comments below helped me find this solution, Thanks to everyone!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With