【问题标题】:How to compare the difference between two periods of time using DateTime? [closed]如何使用 DateTime 比较两个时间段之间的差异? [关闭]
【发布时间】:2013-12-06 15:53:19
【问题描述】:

我有一个类,它有两个日期时间(开始和结束)和一个标志(原始),在该时间段内必须是唯一的“真”。

public class ClassTest
{
    public long Id { get; set; }
    public string Description { get; set; }
    public bool Primal { get; set; }
    public DateTime Begin { get; set; }
    public Nullable<DateTime> End { get; set; }
}

如果有一个 ClassTest 填充了 'Description' = "Whatever" 'Primal' = true,'begin' = 06/12/2013 和 'End' = 10/12/2013,我尝试插入另一个对象'Primal' = true,'begin' = 05/12/2013 和 'End' = null,应用程序必须返回(通过一个类上的链接,该类验证在我的时间段内没有任何其他对象 'primal'试图插入)那已经是第二个对象期间的对象。

【问题讨论】:

  • 不清楚你想做什么。你会在哪里插入ClassTest 对象?您能给我们提供样本输入和预期结果吗?
  • 您可以比较 DateTimes,就像您对任何其他类型进行比较一样。以任何你想要的方式完成其余的逻辑。不,没有神奇的功能可以完全按照您的意愿行事。
  • 非常不清楚你在问什么。
  • 您更新的问题很清楚这与日期时间无关。您只想浏览您收藏中的所有项目,比较它们各自的开始日期和结束日期并进行验证。

标签: c# asp.net datetime logic


【解决方案1】:
public static bool IsValid(ClassTest current, ClassTest other)
{
    if (!other.Primal || !current.Primal)
        return true;
    if (current.End.HasValue 
        && other.End.HasValue
        && (other.End.Value <= current.Begin || other.Begin >= current.End.Value))
        return true;
    if (!current.End.HasValue 
        && other.End.HasValue
        && other.End.Value <= current.Begin)
        return true;
    if (current.End.HasValue 
        && !other.End.HasValue
        && other.Begin >= current.End.Value)
        return true;

    return false;
}

var isUnique = existing.All(item => IsValid(item, newItem));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多