C# 如何在C中通过键盘输入日期时间变量#
我需要根据日期/月/年格式从键盘输入数据 我尝试这样的代码:C# 如何在C中通过键盘输入日期时间变量#,c#,date,datetime,input,keyboard,C#,Date,Datetime,Input,Keyboard,我需要根据日期/月/年格式从键盘输入数据 我尝试这样的代码: DateTime dt = new DateTime(); dt = DateTime.Parse(Console.ReadLine()); 但当输入日期时,我还是先输入年份。那么我该如何解决这个问题呢。谢谢 您能在Program.cs中向我展示一下您的主要方法吗?我想知道用逐字字符串文字标记读线是否有帮助。此外,您可能还应该使用TryParse,以便处理 if (!DateTime.TryParse($@"{Conso
DateTime dt = new DateTime();
dt = DateTime.Parse(Console.ReadLine());
但当输入日期时,我还是先输入年份。那么我该如何解决这个问题呢。谢谢 您能在Program.cs中向我展示一下您的主要方法吗?我想知道用逐字字符串文字标记读线是否有帮助。此外,您可能还应该使用TryParse,以便处理
if (!DateTime.TryParse($@"{Console.ReadLine()}", out DateTime result))
{
throw new FormatException("The Date you entered is not a valid date");
}
Console.WriteLine($"{result.ToString("yyyy/MM/dd")}");
你可以看看我的解决方案 如果您查看DateTime构造函数,您将看到构造函数以该顺序接受int year、int month、int day,这与OP的目标格式不匹配。看看我的答案,找到一个简单的解决办法 您还可以在下面找到代码:
string targetDateFormat = "dd/MM/yyyy";
DateTime dt;
Console.WriteLine("Enter a date in the format day/month/year");
string enteredDateString = Console.ReadLine();
//This is assuming the string entered is of the correct format, I suggest doing some validation
dt = DateTime.ParseExact(enteredDateString, targetDateFormat,CultureInfo.InvariantCulture);
//This will print in month/day/year format
Console.WriteLine(dt);
//This will print in day/month/year format
Console.WriteLine(dt.ToString("dd/MM/yyyy"));
您需要在代码中添加以下使用声明:
使用系统全球化代码>别忘了日期格式在世界各地是不同的。英国使用日/月/年,美国使用月/日/年,中国使用年/月/日。除此之外,分隔符也可以不同(有些使用斜杠,有些区域性使用破折号等)
DateTime.Parse
将使用从O/S启动时检测到的区域性。如果要覆盖此区域性,则应使用DateTime.ParseExact
(指定确切模式的位置),或传递DateTime.Parse
要使用的区域性。要开始,必须导入
using System.Globalization;
在你的代码头中,在你把这个代码
DateTime dt;
dt = DateTime.Parse (Console.ReadLine ());
Console.WriteLine (dt.ToString ("d"
CultureInfo.CreateSpecificCulture ("NZ-in")));
Console.ReadLine ();
有关详细信息,请访问此网页
https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings
分析/
上的输入拆分以分离元素,或者使用3个提示。输入的内容可能是这样的DateTime dt=new DateTime();dt=DateTime.ParseExact(Console.ReadLine(),“dd/MM/yyyy”,CultureInfo.InvariantCulture);控制台写入线(dt.ToString(“dd/MM/yyyy”)代码>@ChetanRanpariya程序错误:dt=DateTime.ParseExact(Console.ReadLine(),“dd/MM/yyyy”,CultureInfo.InvariantCulture);程序错误:dt=DateTime.ParseExact(enteredDateString、targetDateFormat、CultureInfo.InvariantCulture);添加使用系统全球化代码>在代码的顶部,输入的日期格式应该是日/月/年,对吗?当您点击run并以上面所述的格式输入日期时,您可以看到这段代码是有效的。我建议从我发布的链接复制代码,并用它替换您的代码,看看会发生什么。你也可以编辑你的帖子,发布你所有的代码,这样我可以进一步帮助你。哦,这很有效!!!非常感谢你!!!当我进入第8天和第08天时,我意识到有很大的不同!!!这使程序错误看看DateTime构造函数。构造函数按该顺序接收int year、int month、int day
,这与OP的目标格式不匹配。请看我的答案,以获得一个简单的解决方案。我们自己在这里没有使用构造函数。我在RoslynPad中尝试过这段代码,它解析的是2016年12月14日和2016年12月14日。哦,对不起,在我发表评论之前,我应该在谷歌上搜索tryparse的文档。很好的解决方案。