2012-02-18 61 views
-5

這一個讓我很難過,因爲我不認爲這可以通過一個簡單的DateTime方法來完成,除非我沒有理解。屬性返回單獨的月份,日期,年份屬性格式化?

它應該是簡單這樣的:格式化變量在XX/XX/XXXX格式來讀取,並且如果這些整數中的一個是0,一個控制檯輸出應該讀~~未指定~~

namespace TheTime 
    { 
     public class Time 
     { 
      private int month; 
      private int day; 
      private int year; 

      public int Mont{} 
      public int Day {} 
      public int Year {} 
+0

作業問題:(你有什麼試過的? – 2012-02-18 08:52:35

回答

1

將此方法添加到您的Time課程中。

public string FormattedDate() 
{ 
    if (month == 0 || day == 0 || year == 0) 
     return string.empty; 

    DateTime dt = new DateTime(year, month, day); 
    return dt.ToString("d"); // returns mm/dd/yyyy 
} 

然後使用它:

string sDate = myTimeObj.FormattedDate(); 

if(sDate == string.empty) 
{ 
    Console.WriteLine("~~unspecified~~"); 
} 
else 
{ 
    // it worked fine 
} 
1
public class Time 
{ 
    private int month; 
    private int day; 
    private int year; 

    public override string ToString() 
    { 
      if(month == 0 || day == 0 || year == 0) 
      { 
       return "~~unspecified~~"; 
      } 
      DateTime date = new DateTime(year, month, day); 
      return date.ToString(); 
    } 
} 
+0

ooooh,類似於我的回答,但我更喜歡這個,+1 – 2012-02-18 09:05:28

0

你需要得到使用的ReadLine

字符串

U可以使用ParseExact法這樣

DateTime yourdate = DateTime.ParseExact(your_read_string, "dd/MM/yyyy", CultureInfo.InvariantCulture) 
2

這不是非常清楚你的意思是什麼。但是,如果你想讀從控制檯的日期和失敗,如果它不成功,你可以做這樣的事情:

string dateString = …; 
DateTime date; 
if (!DateTime.TryParseExact(
    dateString, "dd/MM/yyyy", 
    CultureInfo.InvariantCulture, DateTimeStyles.None, out date)) 
{ 
    Console.WriteLine("~~unspecified~~"); 
    return; 
} 

//work with date 

如果dateString在任何部件包含0,或者如果它被格式化錯誤地,此代碼寫入~~unspecified~~並且不會繼續。

相關問題