C#控制台应用程序... 用户如何在同一行中以预格式字符串“ / /”(日期/月/年)给出出生日期; 可以在下一个步骤之前重新检查或更改字符串中的值; 非常感谢...
答案 0 :(得分:0)
嗨,您必须像这样使用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();
希望对您有帮助
答案 1 :(得分:0)
如果要为指定的DateTime“重新检查或更改值”,我建议您使用以下代码:
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日期= 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”更改为您想要的格式。
答案 2 :(得分:0)
Console.WriteLine("Enter day of birth");
DateTime dayOfBirth = Convert.ToDateTime(Console.ReadLine());
现在您可以操纵时间了。