在C#中将时间设置为TimeSpan.MaxValue的正确方法

时间:2011-09-11 13:27:23

标签: c# date

以下代码是否正确?

[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;
}

我希望start09/11/2011 00:00end类似09/11/2011 23:59

4 个答案:

答案 0 :(得分:1)

有几件事......

DateTime.TryParse会自动将out参数初始化为默认值。 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);
}

答案 1 :(得分:1)

不,TimeSpan.Min / MaxValue是非常大的值。不确定你真正想要做什么,但你给出的例子是由:

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

答案 2 :(得分:1)

TimeSpan并非主要用于表示一天中的某个时段,而是表示任何时间间隔,即使它是几天,几个月甚至几年。

由于这个TimeSpan.MaxValue大约需要2万年,而且您的代码会引发异常。

答案 3 :(得分:0)

根据Paul Walls的回答,我接受了这个:

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

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