2011-09-11 22 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年,并且您的代码会引发异常。

相关问题