C# - 一分钟2日期时间之间持续时间 [英] C# - Duration between two DateTimes in minutes

查看:200
本文介绍了C# - 一分钟2日期时间之间持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以分钟2日期时间之间,以确定持续时间

I need to determine duration between two DateTimes in minutes.

然而,有一个轻微的扭曲

However, there is a slight twist:


  • 不包括周末

  • 只算分钟
    这是上午7:00和下午7:00之间。
    例如: [2010年9月30日六时39分00秒
    PM] - [2010年9月30日下午7时39分00秒] = 21
    分钟

  • exclude weekends
  • only count minutes which are between 7:00AM and 7:00PM. for example: [09/30/2010 6:39:00 PM] - [09/30/2010 7:39:00 PM] = 21 Minutes

我只是有一个很难想出一个体面的方式来做到这一点,并会不胜感激,如果任何人都可以提出一些东西。

I'm just having a hard time coming up with a decent way to do it and would appreciate if anyone can suggest something.

感谢。

编辑:

我结束了DTB的解决方案去。只有其中一个需要被照顾的特殊情况:如果结束时间为下午7:00后,计数从上午7:00至实际结束时间的分钟

I ended up going with dtb's solution. There is only one special case which needed to be taken care of: if end time is after 7:00PM, count the minutes from 7:00AM to the actual end time.

这是我修改了它:

var minutes = from day in start.DaysInRangeUntil(end)
                where !day.IsWeekendDay()
                let st = Helpers.Max(day.AddHours(7), start)
                let en = (day.DayOfYear == end.DayOfYear ? 
                            end :
                            Helpers.Min(day.AddHours(19), end)
                            )
                select (en - st).TotalMinutes;

再次感谢您的帮助。

推荐答案

可以,当然,使用LINQ:

You can, of course, use LINQ:

DateTime a = new DateTime(2010, 10, 30, 21, 58, 29);
DateTime b = a + new TimeSpan(12, 5, 54, 24, 623);

var minutes = from day in a.DaysInRangeUntil(b)
              where !day.IsWeekendDay()
              let start = Max(day.AddHours( 7), a)
              let end   = Min(day.AddHours(19), b)
              select (end - start).TotalMinutes;

var result = minutes.Sum();

// result == 6292.89



(注意:您可能需要查了很多一角的情况下,我完全忽略了)

(Note: You probably need to check for a lot of corner cases which I completely ignored.)

helper方法:

static IEnumerable<DateTime> DaysInRangeUntil(this DateTime start, DateTime end)
{
    return Enumerable.Range(0, 1 + (int)(end.Date - start.Date).TotalDays)
                     .Select(dt => start.Date.AddDays(dt));
}

static bool IsWeekendDay(this DateTime dt)
{
    return dt.DayOfWeek == DayOfWeek.Saturday
        || dt.DayOfWeek == DayOfWeek.Sunday;
}

static DateTime Max(DateTime a, DateTime b)
{
    return new DateTime(Math.Max(a.Ticks, b.Ticks));
}

static DateTime Min(DateTime a, DateTime b)
{
    return new DateTime(Math.Min(a.Ticks, b.Ticks));
}

这篇关于C# - 一分钟2日期时间之间持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆