2016-12-24 192 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

爲什麼我的問題被降低了? –