1

我要提前说,我是编程的初学者,这个问题似乎无关紧要。但是,我真的很想知道在这种情况下如何进行。

这是我的代码:

string startdate;

Console.WriteLine("Please, type in your birthdate (dd-mm-yyyy)");
startdate = Console.ReadLine();
DateTime bday = DateTime.Parse(startdate);
        // prob 1.
DateTime now = DateTime.Now;
TimeSpan ts1 = now.Subtract(bday);
DateTime dt = new DateTime(0001, 01, 01);
TimeSpan ts2 = new TimeSpan(365, 0, 0, 0);
        //prob2.
TimeSpan ts3 = new TimeSpan(3650, 0, 0, 0);
dt = dt + ts1 - ts2;
Console.WriteLine("Your current age is:{0}", dt.ToString("yy"));
dt = dt + ts3;
Console.WriteLine("Your Age after 10 years will be:{0}", dt.ToString("yy"));

问题 1:我想创建一个循环,如果控制台中给出的信息与 不同dd-mm-yyyy,则再次重复整个过程。

问题 2:我想看看下一年(从当前一年)是否是闰年,从而知道ts2应该是 365 天还是 366 天。

先感谢您。

4

3 回答 3

1

回覆。问题1:

看一下DateTime.TryParseExact:这允许您指定格式,而不是在输入格式不匹配时抛出异常返回 false。因此

DateTime res;
String inp;
do {
  inp = Console.ReadLine("Date of birth: ");
} while (!DateTime.TryParseExact(inp, "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.None, out res));

回复,问题 2:请参阅DateTime.AddYearsQ 的评论中所述。

于 2014-04-01T10:12:40.140 回答
0

由于Framewrok,闰年问题并不是真正的问题

int daysToAdd = 0;
for(int i = 1; i <= 10; i++)
   daysToAdd += (DateTime.IsLeapYear(DateTime.Today.Year + i) ? 366 : 365);

第一个问题可以解决

DateTime inputDate;
while(true)
{
    Console.WriteLine("Please, type in your birthdate (dd-mm-yyyy)");
    string startdate = Console.ReadLine();
    if(DateTime.TryParseExact(startdate, "dd-MM-yyyy", CultureInfo.CurrentCulture, DateTimeStyles.None, out inputDate))
        break;
}
于 2014-04-01T10:10:00.667 回答
0

问题1:

这可以使用while循环来解决。

while(!DateTime.Parse(startdate))// The "!" is for NOT
{
    Console.WriteLine("Incorrect format please type your birthday again(dd-mm-yyyy)");
    startdate = Console.ReadLine();
}

然而,这带来了另一个问题 DateTime.Parse 将在字符串不正确时抛出错误。(http://msdn.microsoft.com/en-us/library/1k1skd40%28v=vs.110%29.aspx

为了解决这个问题,您需要使用 try catch 子句来“捕获”错误。

在此处查看更多详细信息(http://msdn.microsoft.com/en-us/library/0yd65esw.aspx)因此代码将如下所示:

bool isCorrectTime = false;
while(!isCorrectTime) // The "!" is for NOT
{
    try
    {
        Console.WriteLine("Incorrect format please type your birthday again(dd-mm-yyyy)");
        startdate = Console.ReadLine();
        isCorrectTime = true; //If we are here that means that parsing the DateTime
        // did not throw errors and therefore your time is correct!
    }
    catch
    {
        //We leave the catch clause empty as it is not needed in this scenario
    }

}

对于问题 2,请参阅史蒂夫的回答。

于 2014-04-01T10:17:23.017 回答