2016-12-24 13 views
-1

もう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

今日の日付を取ると生年月日を引く、それはあなたがあなたから必要な情報を取得するために使用できるTimeSpanオブジェクトを与える必要があります。 – 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文字列(例えば、12.12.2018または12/12/2018など)を指定して、 'DateTime'オブジェクトを返すフレームワークメソッドです。 C#は強く型付けされているため、文字列にすることはできません。また、代入演算子の右部分が確定的である場合には、 'var'キーワードを使用することをお勧めします。答えがあなたのために働くなら、それを合格とマークすることを検討してください。 – zaitsman

+0

なぜ私の質問は下落したのですか? –

関連する問題