C#中的天数计算器

时间:2015-07-04 17:52:16

标签: c# visual-studio-2015 string-to-datetime

我一直在尝试用C#创建一个Days on Earth计算器,用户可以用MM / DD / YYYY格式输入他们的生日,并了解他们在这个地球上已经有多长时间了(以天为单位)。我已经检查了一个类似的问题,有人在2年前发布了一个标题为“用户已活多少天计算器”的问题。但我的问题在于格式异常。这是我试图做的事情(我在这方面很新):

Console.WriteLine("Welcome to the Days on Earth Finder!" +
"\nPlease input your birthday(MM/DD/YYY):");
Console.ReadLine();

//string myBirthday = Console.ReadLine();
//DateTime mB = Convert.ToDateTime(myBirthday);
//DateTime myBirthday = DateTime.Parse(Console.ReadLine());
string myBirthday = Console.ReadLine();
DateTime mB = DateTime.Parse(myBirthday); //This line is where the error occurs
TimeSpan myAge = DateTime.Now.Subtract(mB);

Console.WriteLine("You are " + myAge.TotalDays + " days old!");
Console.ReadLine();

我离开了之前的尝试,注意到它是否有帮助。 出现的错误如下:

  

mscorlib.dll中发生未处理的“System.FormatException”类型异常

     

其他信息:字符串未被识别为有效的DateTime。

虽然当我给它一个字符串文字时,它可以工作,例如“8/10/1995”。

DateTime myBirthday = DateTime.Parse("8/10/1995");
TimeSpan myAge = DateTime.Now.Subtract(myBirthday);
Console.WriteLine("You are " + myAge.TotalDays + " days old!");
Console.ReadLine();

如果有帮助,我也在使用Visual Studio 2015社区RC。

3 个答案:

答案 0 :(得分:1)

你可以尝试这样的事情:

string birthDateString = "5/2/1992";
DateTime birthDate;
if (DateTime.TryParse(birthDateString, out birthDate))
{
    DateTime today = DateTime.Now;
    Console.WriteLine("You are {0} days old", (today - birthDate).Days);
}
else Console.WriteLine("Incorrect date format!");

答案 1 :(得分:1)

您有两个Console.ReadLine();语句。

您可能需要按两次输入。

删除第一个Console.ReadLine();,它会在您填写日期时生效。

答案 2 :(得分:1)

您将其编码为读取输入两次,第二次是将输入用作日期,但是您可能按下输入(这不是日期)并且它给出了FormatException。
ReadLine()。

Console.WriteLine("Welcome to the Days on Earth Finder!" +
"\nPlease input your birthday(MM/DD/YYY):");
//Console.ReadLine();

//string myBirthday = Console.ReadLine();
//DateTime mB = Convert.ToDateTime(myBirthday);
//DateTime myBirthday = DateTime.Parse(Console.ReadLine());
string myBirthday = Console.ReadLine();
DateTime mB = DateTime.Parse(myBirthday);
//This line is where the error occurs
TimeSpan myAge = DateTime.Now.Subtract(mB);

Console.WriteLine("You are " + myAge.TotalDays + " days old!");
Console.ReadLine();