2011-09-11 23 views
0

下面的代碼是否正確?正確設置C中TimeSpan.MaxValue的時間的方法#

[WebMethod] 
[ScriptMethod] 
public bool DoPost(CommunityNewsPost post) 
{ 
    MembershipHelper.ThrowUnlessAtLeast(RoleName.Administrator); 

    DateTime? start; 
    DateTime? end; 

    Utility.TryParse(post.PublishStart, out start); 
    Utility.TryParse(post.PublishEnd, out end); 

    if (start != null) 
     start -= start.Value.TimeOfDay - TimeSpan.MinValue; 

    if(end!=null) 
     end += TimeSpan.MaxValue - end.Value.TimeOfDay; 

    return CommunityNews.Post(post.Title, post.Markdown, post.CategoryId, start, end); 
} 

而且Utility.TryParse

public static bool TryParse(string s, out DateTime? result) 
{ 
    DateTime d; 
    var success = DateTime.TryParse(s, out d); 
    if (success) 
     result = d; 
    else 
     result = default(DateTime?); 

    return success; 
} 

我想start是像09/11/2011 00:00end是像09/11/2011 23:59

+0

您不使用'Utility.TryParse()'的返回值,它包含在'result'中。我認爲你應該讓它返回結果。 – svick

+0

我不使用它*這次*,我**可能**將來使用它。此外,每個TryParse方法都遵循這種模式。 – bevacqua

+1

這就是每個'TryParse()'遵循的模式*,因爲它不返回可爲空的值*。你需要一些方法來表示失敗。 'TryParse'使用'false'的返回值,你可以使用'null'。 – svick

回答

1

沒有,TimeSpan.Min/MaxValue的是非常大的值。不是說知道你真正想要做的,而是由生成你給的例子:

 if (start != null) start = start.Value.Date; 
     if (end != null) end = start.Value.Date.AddDays(1).AddSeconds(-1); 
1

幾件事情......

DateTime.TryParse會自動初始化out參數爲默認值UE。 Utility.TryParse可能沒有理由存在。

其次,看看DateTime.Date,這可能是您試圖複製的內容。

編輯:我忽略了Nullable類型。你可以重構爲這樣的事情:

public bool DoPost(CommunityNewsPost post) 
{ 
    MembershipHelper.ThrowUnlessAtLeast(RoleName.Administrator); 

    DateTime value; 
    DateTime? start; 
    DateTime? end; 

    DateTime.TryParse(post.PublishStart, out value); 
    start = (value != DateTime.MinValue) ? new DateTime?(value.Date) : null; 
    DateTime.TryParse(post.PublishEnd, out value); 
    end = (value != DateTime.MinValue) ? 
     new DateTime?(value.Date.AddMinutes(-1.0)) : null; 

    return CommunityNews.Post(post.Title, post.Markdown, post.CategoryId, 
     start, end); 
} 
+0

'DateTime'不能轉換爲'DateTime?'(我不想在我的方法中每次解析爲DateTime時聲明'DateTime'? ')這就是我的方法的原因。絕對我想要DateTime.Date,謝謝! – bevacqua

+0

另外'TimeSpan'可以超過一天。 'TimeSpan.MaxValue'類似[10萬天](http://msdn.microsoft.com/en-us/library/system.timespan.maxvalue.aspx)。還要注意,在.NET中表示的當天的最新點是23:59.9999999,ConmunityPost可能會在第二天很好地回合 –

+0

@Nico是的,我的速度太快了。我編輯了Nullable類型的答案。 –

0

基於保牆的回答,我這個去:

if (start != null) 
    start = start.Value.Date; 

if (end != null) 
    end = end.Value.Date + new TimeSpan(23, 59, 59); 
1

TimeSpan的主要目的不是代表一天的時間,但表示任何時間間隔,即使是數天,幾個月甚至幾年。

由於這個TimeSpan.MaxValue大約是20 000年,並且您的代碼會引發異常。

相關問題