将一天的时间设置为TimeSpan的正确方法.c#中的MaxValue

本文关键字:方法 中的 MaxValue TimeSpan 一天 时间 设置 | 更新日期: 2023-09-27 18:08:20

以下代码正确吗?

[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:00的东西end是类似09/11/2011 23:59的东西

将一天的时间设置为TimeSpan的正确方法.c#中的MaxValue

TimeSpan主要不是用来表示一天中的时间,而是用来表示任何时间间隔,即使是几天、几个月甚至几年。

因为TimeSpan.MaxValue大约是20000年,你的代码抛出一个异常

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

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

根据Paul Walls的回答,我选择了这个:

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

有几件事…

DateTime.TryParse将自动初始化out参数为默认值。Utility.TryParse可能没有存在的理由。

第二,看一下DateTime。日期,这可能是您要复制的。 编辑:我忽略了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);
}