繁体   English   中英

DateTime格式-在C#中获取System.FormatException

[英]DateTime Format - Getting System.FormatException in c#

我是C#的新手。我正在编写一个约会计划程序,该程序中我想从控制台以字符串形式提供Date和Time值,然后将其解析为DateTime格式。 但是通过这样做我得到了

“ System.FormatException”-字符串未被识别为有效的日期时间

这是我的代码,

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);

当我完全按照格式(即像23/11/2012 08:30 pm)提供输入时。我遇到了上述异常。 我想用AM/PM输出datetime。 我做错了什么?

这个问题有点奇怪,因为格式字符串可以与给定的输入字符串一起使用(在所有区域性中),并且您希望以相同的格式输出。 也许有人进入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);

输出: 23/11/2012 08:30 PM

示范

请注意,您始终可以使用DateTime.TryParseExact来验证用户输入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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