2010-10-04 57 views
1

我有一個開始和開始日期時間爲在該事件的開始和結束時記錄的轉換。然後生成一個報告,列出一系列關於事件的信息,包括其運行時間。我有一個總時間(以天爲單位)的列和一個開始和結束的日期表示。一切都在幾天,我不關心小時/分鐘/秒。C#通過兩個日期字符串的寫入時間

如果啓動時間是9/29/2010和結束時間爲2010年9月31日我想打印:

9/29-31/2010 

如果啓動時間是9月29日/ 2010和結束時間爲2010年10月2日我想打印:

9/29-10/2/2010 

如果啓動時間爲1 2010年2月29日和結束時間是2011年1月2日我想打印:

12/29/2010-1/2/2011 

我知道我可以使用日期時間的的ToString(「M/d/yyyy的」)方法來打印每個日期,但我希望能以簡單的方式以相似的格式打印兩個日期。

回答

3

你的規則非常簡單翻譯成代碼,無需獲得幻想。

static string GetDateRangeString(DateTime startDate, DateTime endDate) 
{ 
    if (endDate.Year != startDate.Year) 
    { 
     return startDate.ToString("M/d/yyyy") + "-" + endDate.ToString("M/d/yyyy"); 
    } 
    else if (endDate.Month != startDate.Month) 
    { 
     return startDate.ToString("M/d") + "-" + endDate.ToString("M/d/yyyy"); 
    } 
    else 
    { 
     return startDate.ToString("M/d") + "-" + endDate.ToString("d/yyyy"); 
    } 
} 

演示:

Console.WriteLine(GetDateRangeString(new DateTime(2010, 9, 29), new DateTime(2010, 9, 30))); 
Console.WriteLine(GetDateRangeString(new DateTime(2010, 9, 29), new DateTime(2010, 10, 30))); 
Console.WriteLine(GetDateRangeString(new DateTime(2010, 9, 29), new DateTime(2011, 1, 30))); 
+0

正是我在想什麼。您可以通過基於日期邏輯選擇格式字符串並在返回語句中執行格式來簡化它。 – tzerb 2010-10-04 03:40:04

+0

該解決方案忽略'startDate'和'endDate'是同一天的情況。 – JaredPar 2010-10-04 03:43:42

+0

謝謝。我絕對不知道DateTime有Year和Month屬性。我認爲這將不得不用正則表達式來完成。我希望我有VS,而不是記事本和csc.exe,但我出於某種原因,我不夠酷。 – Shawn 2010-10-04 03:50:03

0

我認爲你只需要編碼它,只是2,如果陳述...年份不同,是月份不同,否則。

喜歡的東西

if (d1.year == d2.year) 
{ 
    if (d1.month == d2.month) 
    print format 1 
    else 
    print format 2 
} 
else 
    print format 3 
0
// Precondition: dt1 < dt2 
string dateString1 = dt1.ToString("M/d/yyyy"); 
string dateString2 = dt2.ToString("M/d/yyyy"); 
if (dt1.Year == dt2.Year) 
{ 
    dateString1 = dateString1.Substring(0, dateString1.Length - 5); 
    if (dt1.Month == dt2.Month) 
    { 
     dateString2 = dateString2.Substring(dt1.Month < 10 ? 2 : 3); 
    } 
} 
string finalValue = String.Format("{0}-{1}", dateString1, dateString2); 
2

你沒有指定它應如何打印出來,如果他們其實都是相同的日期。在這種情況下假定只打印一個日期。

static string DateRangeToString(DateTime left, DateTime right) { 
    if (left.Year != right.Year) { 
    return String.Format("{0}-{1}", left.ToString("M/d/yyyy"), right.ToString("M/d/yyyy")); 
    } else if (left.Month != right.Month) { 
    return String.Format("{0}-{1}", left.ToString("M/d"), right.ToString("M/d/yyyy")); 
    } else if (left.Day != right.Day) { 
    return String.Format("{0}-{1}", left.ToString("M/d"), right.ToString("d/yyyy")); 
    } else { 
    return left.ToString("M/d/yyyy"); 
    } 
}