简体   繁体   中英

error “String was not recognized as a valid DateTime.” in c#

I have created an android application in which I have used android date picker. While submitting form in my application I am getting date in this format "18-2-2021" and I want to format this date in "18-Feb-2021" format. I don't want to force my user to update application so I want to format date in my c# web service code.

I am trying to format date using below code but I am getting " String was not recognized as a valid DateTime. ".

DateTime requestRaisedDate = DateTime.ParseExact(ApplicationID.REQUEST_RAISED_DATE, "dd-MM-yyyy",System.Globalization.CultureInfo.InvariantCulture);

With 18-2-2021 you need to allow single-digit months: dd-M-yyyy :

DateTime requestRaisedDate = DateTime.ParseExact(ApplicationID.REQUEST_RAISED_DATE, "dd-M-yyyy",System.Globalization.CultureInfo.InvariantCulture);

This allows 18-2-2021 and also 18-02-2021 .

See: https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#month-m-format-specifier

DateTime requestRaisedDate = DateTime.ParseExact(ApplicationID.REQUEST_RAISED_DATE, "dd-M-yyyy",System.Globalization.CultureInfo.InvariantCulture);

Use Single M for single-digit month. It will support 10, 11,12 by default. So, don't worry

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM