2016-12-24 212 views
-1

另一个新手问题。我正在尝试创建一个年龄计算器,它将用户的年龄,然后从当前日期中减去并显示给用户。 我已经有了基本的想法。 这里是我的示例代码:如何创建一个年龄计算器,以年,日,年来讲述年龄?

using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Text; 
    using System.Threading.Tasks; 

    namespace Age_Calculator 
    { 
     class Program 
    { 
     static void Main(string[] args) 
     { 

      DateTime Current = DateTime.Now; 
      Console.WriteLine("Please enter your birth date: "); 
      string myBirthDate = Console.ReadLine(); 
      //ive got the date from the user, now how do i subtract the current date from the date of birth? 
      string myAge = //here the result is stored 
          //then displayed as hours 
          //then displayed as days 
          //finally as years 
          //will use replacement code i think 
      Console.WriteLine(myAge); 

      //Ive got the idea but due to lack of knowledge i cant make this application 



     } 
    } 
    } 
+0

采取今天的日期和减去诞生之日起,它应该给一个时间跨度的对象,你可以用它来得到你需要的信息。 – Jite

回答

0

试试这个:

static void Main(string[] args) 
     { 

      DateTime Current = DateTime.Now; 
      Console.WriteLine("Please enter your birth date: "); 
      string myBirthDate = Console.ReadLine(); 
      var birthDate = DateTime.Parse(myBirthDate); 

      TimeSpan myAge = Current - birthDate; 
      Console.WriteLine($"Hours: {myAge.TotalHours}"); 
      Console.WriteLine($"Days: {myAge.TotalDays}"); 
      Console.WriteLine($"Years: {Current.Year - birthDate.Year}"); 

      Console.WriteLine(myAge); 
     } 
+0

,完美的工作!非常感谢!你能给我一些关于.Parse的解释吗?为什么在birthDate中使用var?为什么不一个字符串? –

+0

'DateTime.Parse()'是一个框架方法,它返回给定有效ish字符串的DateTime对象(例如12.12.2018或12/12/2018或类似的)。它不能是一个字符串,因为c#是强类型的。另外,当赋值运算符的右部分是确定性的时候,使用'var'关键字是一个好习惯。如果答案适合您,请考虑将其标记为已接受。 – zaitsman

+0

为什么我的问题被降低了? –