[英]C# Console Date Input
C# 控制台应用程序...用户如何在同一行的预格式字符串“//”(日期/月/年)中给出他的出生日期; 可以在下一个程序之前重新检查或更改字符串中的值; 非常感谢...
嗨,你必须像这样使用 split
Console.WriteLine("Please Enter Your DateTime: \n");
//you input your string dateTime Like 2/12/2013
string DateInput = Console.ReadLine();
//split it
string[] DateTimeArray = DateInput.Split('/');
//String DateTime
string ResultStringDateTime="";
//this loop is for create string DateTime with Type Like 2-12-2013
for (int i = 0; i < DateTimeArray.Length; i++)
{
if (i==2)
{
ResultStringDateTime += DateTimeArray[i];
continue;
}
ResultStringDateTime += DateTimeArray[i]+"-";
}
//if u want change you must change in this line
//this is DateTime Type Of your DateTime
DateTime myDate;
//in this step if you have error this will be message else create date time
try
{
//out String DateTime
myDate = Convert.ToDateTime(ResultStringDateTime);
Console.WriteLine(myDate.ToShortDateString());
}
catch (Exception e)
{
Console.WriteLine("err "+e.Message );
}
Console.ReadLine();
我希望会有所帮助
如果您想为指定的日期时间“重新检查或更改值”,我建议您使用以下代码:
Console.Write("Enter a date:");
string input = Console.ReadLine(), format = "";
try
{
if (input.Contains("-"))
{
format = "dd-MM-yyyy";
}
else if (input.Contains("/"))
{
format = "dd/MM/yyyy";
}
else if (input.Contains("."))
{
format = "dd.MM.yyyy";
}
else if (input.Contains(" "))
{
format = "dd MM yyyy";
}
DateTime date = DateTime.ParseExact(input, format, System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(date.ToShortDateString());
}
catch (Exception) { }
Console.ReadLine();
使用此代码片段,您可以使用任何您想要的输入...
DateTime date = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture);
...您只需要将格式“yyyy-MM-dd HH:mm:ss,fff”更改为您想要的格式。
Console.WriteLine("Enter day of birth");
DateTime dayOfBirth = Convert.ToDateTime(Console.ReadLine());
现在你可以操纵你的时间了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.