I am very new to C#.. I am writing an appointment schedule program where in I want to provide Date and Time value as a string from console and then I want to parse it to DateTime
format. But by doing so I am getting
"System.FormatException" - string was not recognized as a valid datetime
Here is my piece of code,
string Format = "dd/MM/yyyy hh:mm tt";
Console.WriteLine("Enter the appointment date and time in(dd/MM/yyyy hh:mm AM/PM) format");
User_Input = Console.ReadLine();
Date_Time = DateTime.ParseExact(User_Input,Format,CultureInfo.InvariantCulture);
When I provide input exactly as format ie like 23/11/2012 08:30 pm.. I am getting the said exception. I want to output datetime with AM/PM
. What have I done wrong?
The question is a little bit odd since your format string works with your given input string(in all cultures) and you want to output with the same format. Perhaps somebody entered 23/11/2012 18:30 pm
instead which does not work with the AM/PM designator.
string format = "dd/MM/yyyy hh:mm tt";
DateTime dateTime = DateTime.ParseExact("23/11/2012 08:30 pm", format, CultureInfo.InvariantCulture);
string output = dateTime.ToString(format, CultureInfo.InvariantCulture);
outputs: 23/11/2012 08:30 PM
Note that you can always use DateTime.TryParseExact
to validate user input.
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.