2015-09-03 21 views
-1

我知道我可以做到這一點,它的工作原理有沒有什麼辦法只能通過ReadLine()將Date設置爲DateTime類型的變量?怎麼樣?

string Dob; //string 
Console.WriteLine("Enter date of Birth in format DD/MM/YYYY: "); 
Dob = Console.ReadLine(); 

但我想是這樣的!預定義的方法或shorthad方式

DateTime Dob; //DateTime 
Console.WriteLine("Enter date of Birth in format DD/MM/YYYY: "); 
//What i am expecting, but is not possible as its DateTime 
Dob = Console.ReadLine(); // expects a string 

有沒有從鍵盤獲取日期只到多波變直接具體的方法。

在DateTime類中是否有預定義的方法? 達到此目的的最佳方式或最短途徑是什麼?

+5

'DateTime.Parse(Console.ReadLine())'? – cubrr

+1

@cubrr它不適合我,它會拋出System.FormatException – Black0ut

+1

然後你給它的日期格式不正確。 – cubrr

回答

0

到目前爲止,這是我發現,作爲cubrr評論的最簡單和最簡單的辦法。

DateTime Dob; 
Console.WriteLine("Enter date of Birth in format MM/DD/YYYY: "); 
//accepts date in MM/dd/yyyy format 
Dob = DateTime.Parse(Console.ReadLine()); 
5
string line = Console.ReadLine(); 
DateTime dt; 
while (!DateTime.TryParseExact(line, "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out dt)) 
{ 
    Console.WriteLine("Invalid date, please retry"); 
    line = Console.ReadLine(); 
} 
+0

這適用,但在我所在的地區芝加哥,伊利諾伊州默認的日期風格是MM/DD/YYYY。也許這是沒有設置爲DateTimeStyles屬性的默認值。你的意思是輸入mm/dd/yyyy而不是dd/mm/yyyy。另外,我完全看到了我們的日期格式的不合邏輯性質,因爲它應該從最大到最小或其他方式,但是在調試這些代碼時我有點困惑。 –

1

此方法轉換使用指定的格式和區域性特定格式的信息的日期和時間的日期時間其等效的指定字符串表示。字符串表示的格式必須完全匹配指定的格式。

DateTime myDate = DateTime.ParseExact("2009/05/08","yyyy/MM/dd", 
System.Globalization.CultureInfo.InvariantCulture) 
+0

謝謝你發佈這個問題的答案! Stack Overflow不鼓勵使用代碼解答,因爲沒有上下文的代碼轉儲並不能解釋解決方案如何或爲什麼會起作用,這使原始海報(或任何未來的讀者)很難理解其背後的邏輯。請編輯你的問題,幷包括你的代碼的解釋,以便其他人可以從你的答案中受益。謝謝! –

1

您可以通過編寫擴展函數來擴展.net中的字符串類,如下所示。

public static class Extensions 
{ 
    public static DateTime? Dob(this string strLine) 
    { 
     DateTime result; 
     if(DateTime.TryParseExact(strLine, "dd/MM/yyyy",System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal,out result)) 
     { 
      return result; 
     } 
     else 
     { 
      return null; 
     } 
    } 
} 

然後,您可以使用它的任何字符串對象。看下面的例子來看看我在說什麼。

class Program 
{ 
    static void Main(string[] args) 
    { 
     Console.WriteLine("Please enter your date of birth in DD/MM/YYYY:"); 

     // Option 1. 
     // The Console.ReadLine() function returns a string. 
     string strDob = Console.ReadLine(); 
     DateTime? dob1 = strDob.Dob(); 


     // Option 2. 
     // You can combine the two steps together into one line for smoother reading. 
     DateTime? dob = Console.ReadLine().Dob();    
    } 
} 

注意:DateTime類型末尾的問號(?)將DateTime「struct」轉換爲可爲空的「對象」。如果將DateTime「struct」設置爲null,它會在DateTime中引發異常?可以設置爲空。考慮使用DateTime是一個好習慣嗎? (空),而不是使用DateTime「結構」

相關問題