[英]DateTime Format - Getting System.FormatException in c#
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. 我是C#的新手。我正在编写一个约会计划程序,该程序中我想从控制台以字符串形式提供Date和Time值,然后将其解析为
DateTime
格式。 But by doing so I am getting 但是通过这样做我得到了
"System.FormatException" - string was not recognized as a valid datetime
“ System.FormatException”-字符串未被识别为有效的日期时间
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. 当我完全按照格式(即像23/11/2012 08:30 pm)提供输入时。我遇到了上述异常。 I want to output datetime with
AM/PM
. 我想用
AM/PM
输出datetime。 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. 也许有人进入
23/11/2012 18:30 pm
,这与AM / PM指示符不兼容。
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
输出:
23/11/2012 08:30 PM
Note that you can always use DateTime.TryParseExact
to validate user input. 请注意,您始终可以使用
DateTime.TryParseExact
来验证用户输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.