AddBusinessDaysおよびGetBusinessDays


93

私は2つのエレガントで完全な実装を見つける必要があります

public static DateTime AddBusinessDays(this DateTime date, int days)
{
 // code here
}

and 

public static int GetBusinessDays(this DateTime start, DateTime end)
{
 // code here
}

O(1)が望ましい(ループなし)。

編集:営業日とは、営業日(月、火、水、木、金)を意味します。休日はなく、週末のみが除外されます。

私はすでに機能しているように見える醜い解決策をいくつか持っていますが、これを行うためのエレガントな方法はあるのでしょうか。ありがとう


これは私がこれまで書いたものです。それはすべてのケースで機能し、ネガも行います。GetBusinessDays実装がまだ必要です

public static DateTime AddBusinessDays(this DateTime startDate,
                                         int businessDays)
{
    int direction = Math.Sign(businessDays);
    if(direction == 1)
    {
        if(startDate.DayOfWeek == DayOfWeek.Saturday)
        {
            startDate = startDate.AddDays(2);
            businessDays = businessDays - 1;
        }
        else if(startDate.DayOfWeek == DayOfWeek.Sunday)
        {
            startDate = startDate.AddDays(1);
            businessDays = businessDays - 1;
        }
    }
    else
    {
        if(startDate.DayOfWeek == DayOfWeek.Saturday)
        {
            startDate = startDate.AddDays(-1);
            businessDays = businessDays + 1;
        }
        else if(startDate.DayOfWeek == DayOfWeek.Sunday)
        {
            startDate = startDate.AddDays(-2);
            businessDays = businessDays + 1;
        }
    }

    int initialDayOfWeek = (int)startDate.DayOfWeek;

    int weeksBase = Math.Abs(businessDays / 5);
    int addDays = Math.Abs(businessDays % 5);

    if((direction == 1 && addDays + initialDayOfWeek > 5) ||
         (direction == -1 && addDays >= initialDayOfWeek))
    {
        addDays += 2;
    }

    int totalDays = (weeksBase * 7) + addDays;
    return startDate.AddDays(totalDays * direction);
}

14
それが日付のように非論理的なものになると、エレガントなソリューションはありますか?
ワイアットバーネット

あなたは休日に精通していますか?– James Conigliaro。いいえ
Adrian Zanescu 09年

9
助けようとしている人々に投票することは、勝利戦略ではありません。
Jamie Ide、

1
AddBusinessDays上記の質問の実装に関する簡単なメモ(実際には削除を取り消すことを提案した削除済みの回答でした。代わりにmodがその質問への回答をコピーしました):私の意見では、このソリューションはこれまでのすべての回答よりも優れています土曜日と日曜日を負の値として正しく処理し、サードパーティのlibを必要としないもの。(ここでは、さまざまなソリューションをテストする小さなプログラムを作成しました。)if (businessDays == 0) return startDate;このエッジケースでも正しい結果を得るために、メソッドの最初にのみ追加します。
スラウマ14

1
@AZ .:最初の削除はかなり古いものでした。私があなたの回答の削除を取り消すようリクエストした後、MODは回答の削除を取り消し(30秒間)して、質問の下のコンテンツをコピーし、彼はそれを再度削除しました。これが、最近の削除タイムスタンプが回答に含まれている理由です。私の目的のために、あなたAddBusinessDaysが私が必要とするすべてのケースで機能する最も一般的な解決策があなただったので、私は上記のコメントを書きました。私の現在のプロジェクトの1つにそれをコピーしました(わずかな変更とC ++への変換の後)。コードに感謝します:)すべてのエッジケースを正しくすることは驚くほど難しいので、非常に役に立ちました。
スラウマ2014

回答:


134

最初の機能の最新の試み:

public static DateTime AddBusinessDays(DateTime date, int days)
{
    if (days < 0)
    {
        throw new ArgumentException("days cannot be negative", "days");
    }

    if (days == 0) return date;

    if (date.DayOfWeek == DayOfWeek.Saturday)
    {
        date = date.AddDays(2);
        days -= 1;
    }
    else if (date.DayOfWeek == DayOfWeek.Sunday)
    {
        date = date.AddDays(1);
        days -= 1;
    }

    date = date.AddDays(days / 5 * 7);
    int extraDays = days % 5;

    if ((int)date.DayOfWeek + extraDays > 5)
    {
        extraDays += 2;
    }

    return date.AddDays(extraDays);

}

2番目の関数GetBusinessDaysは、次のように実装できます。

public static int GetBusinessDays(DateTime start, DateTime end)
{
    if (start.DayOfWeek == DayOfWeek.Saturday)
    {
        start = start.AddDays(2);
    }
    else if (start.DayOfWeek == DayOfWeek.Sunday)
    {
        start = start.AddDays(1);
    }

    if (end.DayOfWeek == DayOfWeek.Saturday)
    {
        end = end.AddDays(-1);
    }
    else if (end.DayOfWeek == DayOfWeek.Sunday)
    {
        end = end.AddDays(-2);
    }

    int diff = (int)end.Subtract(start).TotalDays;

    int result = diff / 7 * 5 + diff % 7;

    if (end.DayOfWeek < start.DayOfWeek)
    {
        return result - 2;
    }
    else{
        return result;
    }
}

2番目の問題の1つの解決策は、日付と日付+日の間の差を取ることです。これは、2つの機能が正しく同期することを保証し、冗長性を排除するという点で優れています。
ブライアン

現在の日付をフィードし、0〜10営業日実行します。常に水曜日に失敗します。
エイドリアン・ゴドン

1
ええ、私たちは結局そこに着きました。(私は私の小さな貢献に対して「私たち」と言います!)努力に賛成票を投じました。
ノルドリン2009年

あなたの入力Noldorinをありがとう、残念ながら私はあなたのコメントだけを賛成することができます!
Patrick McDonald、

3
DateTime.AddDaysは負の数値で機能します。これは、AddBusinessDaysで負の数を使用すると非営業日を選択できるのと同じパターンに正しく従いません。
リストゴット2014年

63

Fluent DateTimeを使用:

var now = DateTime.Now;
var dateTime1 = now.AddBusinessDays(3);
var dateTime2 = now.SubtractBusinessDays(5);

内部コードは次のとおりです

    /// <summary>
    /// Adds the given number of business days to the <see cref="DateTime"/>.
    /// </summary>
    /// <param name="current">The date to be changed.</param>
    /// <param name="days">Number of business days to be added.</param>
    /// <returns>A <see cref="DateTime"/> increased by a given number of business days.</returns>
    public static DateTime AddBusinessDays(this DateTime current, int days)
    {
        var sign = Math.Sign(days);
        var unsignedDays = Math.Abs(days);
        for (var i = 0; i < unsignedDays; i++)
        {
            do
            {
                current = current.AddDays(sign);
            }
            while (current.DayOfWeek == DayOfWeek.Saturday ||
                current.DayOfWeek == DayOfWeek.Sunday);
        }
        return current;
    }

    /// <summary>
    /// Subtracts the given number of business days to the <see cref="DateTime"/>.
    /// </summary>
    /// <param name="current">The date to be changed.</param>
    /// <param name="days">Number of business days to be subtracted.</param>
    /// <returns>A <see cref="DateTime"/> increased by a given number of business days.</returns>
    public static DateTime SubtractBusinessDays(this DateTime current, int days)
    {
        return AddBusinessDays(current, -days);
    }

これは、VB.Netに変換されたときに実際に機能した唯一のソリューションです
Nicholas

1
OPはループを要求しませんでしたが、このループには明らかにループがあります。最も効率の悪い方法で何かを行うことについて、エレガントなことは何もありません。
Neolisk 2015年

13

営業日を加算または減算できる拡張機能を作成しました。負の数のbusinessDaysを使用して減算します。とてもエレガントな解決策だと思います。すべてのケースで機能するようです。

namespace Extensions.DateTime
{
    public static class BusinessDays
    {
        public static System.DateTime AddBusinessDays(this System.DateTime source, int businessDays)
        {
            var dayOfWeek = businessDays < 0
                                ? ((int)source.DayOfWeek - 12) % 7
                                : ((int)source.DayOfWeek + 6) % 7;

            switch (dayOfWeek)
            {
                case 6:
                    businessDays--;
                    break;
                case -6:
                    businessDays++;
                    break;
            }

            return source.AddDays(businessDays + ((businessDays + dayOfWeek) / 5) * 2);
        }
    }
}

例:

using System;
using System.Windows.Forms;
using Extensions.DateTime;

namespace AddBusinessDaysTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            label1.Text = DateTime.Now.AddBusinessDays(5).ToString();
            label2.Text = DateTime.Now.AddBusinessDays(-36).ToString();
        }
    }
}

ソースの日付が土曜日または日曜日の場合、結果は疑わしいものです。例:土曜日+ 1営業日は火曜日になり、月曜日を期待します。
Slauma

3
@Slauma:これがカナダのほとんどの企業の運営方法です。+1営業日=「翌営業日」。土曜日の場合は火曜日。月曜日は「同じ営業日」になります。
Neolisk 2015年

3
@Slaumaプログラムは意図したとおりに機能します。論理的に考えてください。土曜日にビジネス関連の何かが始まり、その営業日の間に1営業日人々が反応できるようにする必要がある場合、月曜日までに行わなければならないことを伝えるのは理にかなっていますか。
Riegardt Steyn 2016

8

私にとっては、週末をスキップして、否定的または肯定的に進むソリューションが必要でした。私の基準は、それが前進して週末に着陸した場合、月曜日に進む必要があるということでした。週末に戻って着陸した場合、金曜日にジャンプする必要があります。

例えば:

  • 水曜日-3営業日=先週の金曜日
  • 水曜日+ 3営業日=月曜日
  • 金曜日-7営業日=最終水曜日
  • 火曜日-5営業日=最終火曜日

さてあなたはアイデアを得ます;)

私はこの拡張クラスを書いてしまいました

public static partial class MyExtensions
{
    public static DateTime AddBusinessDays(this DateTime date, int addDays)
    {
        while (addDays != 0)
        {
            date = date.AddDays(Math.Sign(addDays));
            if (MyClass.IsBusinessDay(date))
            {
                addDays = addDays - Math.Sign(addDays);
            }
        }
        return date;
    }
}

それは私が他の場所で使用すると便利だと思ったこの方法を使用しています...

public class MyClass
{
    public static bool IsBusinessDay(DateTime date)
    {
        switch (date.DayOfWeek)
        {
            case DayOfWeek.Monday:
            case DayOfWeek.Tuesday:
            case DayOfWeek.Wednesday:
            case DayOfWeek.Thursday:
            case DayOfWeek.Friday:
                return true;
            default:
                return false;
        }
    }
}

あなたはそれを気にしたくない場合は、ちょうど交換することができますif (MyClass.IsBusinessDay(date))場合にif ((date.DayOfWeek != DayOfWeek.Saturday) && (date.DayOfWeek != DayOfWeek.Sunday))

だから今できる

var myDate = DateTime.Now.AddBusinessDays(-3);

または

var myDate = DateTime.Now.AddBusinessDays(5);

いくつかのテストの結果は次のとおりです。

テスト予想結果
水曜日-4営業日木曜日木曜日
水曜日-3営業日金曜日金曜日
水曜日+ 3営業日月曜日月曜日
金曜日-7営業日水曜日水曜日
火曜日-5営業日火曜日火曜日
金曜日+1営業日月曜日月曜日
土曜日+1営業日月曜日月曜日
日曜日-1営業日金曜日金曜日
月曜日-1営業日金曜日金曜日
月曜日+1営業日火曜日火曜日
月曜日+0営業日月曜日月曜日

2番目のメソッドも拡張メソッドにしました:public static bool IsBusinessDay(this DateTime date)
Andy B

2
public static DateTime AddBusinessDays(this DateTime date, int days)
{
    date = date.AddDays((days / 5) * 7);

    int remainder = days % 5;

    switch (date.DayOfWeek)
    {
        case DayOfWeek.Tuesday:
            if (remainder > 3) date = date.AddDays(2);
            break;
        case DayOfWeek.Wednesday:
            if (remainder > 2) date = date.AddDays(2);
            break;
        case DayOfWeek.Thursday:
            if (remainder > 1) date = date.AddDays(2);
            break;
        case DayOfWeek.Friday:
            if (remainder > 0) date = date.AddDays(2);
            break;
        case DayOfWeek.Saturday:
            if (days > 0) date = date.AddDays((remainder == 0) ? 2 : 1);
            break;
        case DayOfWeek.Sunday:
            if (days > 0) date = date.AddDays((remainder == 0) ? 1 : 0);
            break;
        default:  // monday
            break;
    }

    return date.AddDays(remainder);
}

1

私は答えに遅れますが、私は就業日に簡単な操作を行うために必要なすべてのカスタマイズを含む小さなライブラリを作成しました...ここに残します:就業日管理


2
残念ながら、これはGNUライセンスであり、商用アプリの「法的毒」です。これを "MIT"または "Apache"にリラックスする可能性はありますか?
トニーO'Hagan

一部の静的リストは、おそらく(リンクリストではなく)配列である必要があります。
トニーO'Hagan

1
私はライセンスをMITに変更しました(単純なもので何もブロックしたくない)。私はあなたの他の命題を調べます。
骨なし

一部の国では月曜日から金曜日以外の稼働日がある場合があるため、国別の稼働日管理を見るのは興味深いでしょう。
シリアライザ

1

実際の唯一の解決策は、これらの呼び出しで、ビジネスのカレンダーを定義するデータベーステーブルにアクセスすることです。月曜から金曜の週労働時間にコーディングすることはそれほど難しくありませんが、休日の扱いは難しいでしょう。

エレガントでテストされていない部分的なソリューションを追加するために編集されました:

public static DateTime AddBusinessDays(this DateTime date, int days)
{
    for (int index = 0; index < days; index++)
    {
        switch (date.DayOfWeek)
        {
            case DayOfWeek.Friday:
                date = date.AddDays(3);
                break;
            case DayOfWeek.Saturday:
                date = date.AddDays(2);
                break;
            default:
                date = date.AddDays(1);
                break;
         }
    }
    return date;
}

また、ループなしの要件にも違反しました。


土曜日の事件が起こることはないと思います。
CoderDennis 2009年

@Dennis-渡された日付が土曜日の場合。
Jamie Ide、

私はそれを機能させるために自由にコードを編集しました。次回投稿する前にコードをテストしてください、ありがとうございます。
bytecode77

そして、私はゼロの賛成投票がそれ自体のために語ったと思いました。ありがとう!
Jamie Ide

1

今日は土曜日日曜日だけでなく休日も除外する方法を見つける必要があったため、この投稿を復活させます。具体的には、次のようなさまざまな休日を処理する必要がありました。

  • 国に依存しない休日(少なくとも西側諸国では-01、01など)。
  • 計算された休日(イースターやイースター月曜日など)。
  • 国固有の休日(イタリア解放日や米国ID4など)。
  • 町固有の休日(ローマ聖パトロンの日など)。
  • その他のカスタムメイドの休日(「明日のオフィスは閉鎖されます」など)。

結局、私は次のヘルパー/拡張機能クラスのセットを思い付きました。それらは明らかにエレガントではありませんが、非効率的なループを大量に使用するため、問題を完全に解決するには十分です。この投稿では、ソースコード全体を削除します。他の人にも役立つことを願っています。

ソースコード

/// <summary>
/// Helper/extension class for manipulating date and time values.
/// </summary>
public static class DateTimeExtensions
{
    /// <summary>
    /// Calculates the absolute year difference between two dates.
    /// </summary>
    /// <param name="dt1"></param>
    /// <param name="dt2"></param>
    /// <returns>A whole number representing the number of full years between the specified dates.</returns>
    public static int Years(DateTime dt1,DateTime dt2)
    {
        return Months(dt1,dt2)/12;
        //if (dt2<dt1)
        //{
        //    DateTime dt0=dt1;
        //    dt1=dt2;
        //    dt2=dt0;
        //}

        //int diff=dt2.Year-dt1.Year;
        //int m1=dt1.Month;
        //int m2=dt2.Month;
        //if (m2>m1) return diff;
        //if (m2==m1 && dt2.Day>=dt1.Day) return diff;
        //return (diff-1);
    }

    /// <summary>
    /// Calculates the absolute year difference between two dates.
    /// Alternative, stand-alone version (without other DateTimeUtil dependency nesting required)
    /// </summary>
    /// <param name="start"></param>
    /// <param name="end"></param>
    /// <returns></returns>
    public static int Years2(DateTime start, DateTime end)
    {
        return (end.Year - start.Year - 1) +
            (((end.Month > start.Month) ||
            ((end.Month == start.Month) && (end.Day >= start.Day))) ? 1 : 0);
    }

    /// <summary>
    /// Calculates the absolute month difference between two dates.
    /// </summary>
    /// <param name="dt1"></param>
    /// <param name="dt2"></param>
    /// <returns>A whole number representing the number of full months between the specified dates.</returns>
    public static int Months(DateTime dt1,DateTime dt2)
    {
        if (dt2<dt1)
        {
            DateTime dt0=dt1;
            dt1=dt2;
            dt2=dt0;
        }

        dt2=dt2.AddDays(-(dt1.Day-1));
        return (dt2.Year-dt1.Year)*12+(dt2.Month-dt1.Month);
    }

    /// <summary>
    /// Returns the higher of the two date time values.
    /// </summary>
    /// <param name="dt1">The first of the two <c>DateTime</c> values to compare.</param>
    /// <param name="dt2">The second of the two <c>DateTime</c> values to compare.</param>
    /// <returns><c>dt1</c> or <c>dt2</c>, whichever is higher.</returns>
    public static DateTime Max(DateTime dt1,DateTime dt2)
    {
        return (dt2>dt1?dt2:dt1);
    }

    /// <summary>
    /// Returns the lower of the two date time values.
    /// </summary>
    /// <param name="dt1">The first of the two <c>DateTime</c> values to compare.</param>
    /// <param name="dt2">The second of the two <c>DateTime</c> values to compare.</param>
    /// <returns><c>dt1</c> or <c>dt2</c>, whichever is lower.</returns>
    public static DateTime Min(DateTime dt1,DateTime dt2)
    {
        return (dt2<dt1?dt2:dt1);
    }

    /// <summary>
    /// Adds the given number of business days to the <see cref="DateTime"/>.
    /// </summary>
    /// <param name="current">The date to be changed.</param>
    /// <param name="days">Number of business days to be added.</param>
    /// <param name="holidays">An optional list of holiday (non-business) days to consider.</param>
    /// <returns>A <see cref="DateTime"/> increased by a given number of business days.</returns>
    public static DateTime AddBusinessDays(
        this DateTime current, 
        int days, 
        IEnumerable<DateTime> holidays = null)
    {
        var sign = Math.Sign(days);
        var unsignedDays = Math.Abs(days);
        for (var i = 0; i < unsignedDays; i++)
        {
            do
            {
                current = current.AddDays(sign);
            }
            while (current.DayOfWeek == DayOfWeek.Saturday
                || current.DayOfWeek == DayOfWeek.Sunday
                || (holidays != null && holidays.Contains(current.Date))
                );
        }
        return current;
    }

    /// <summary>
    /// Subtracts the given number of business days to the <see cref="DateTime"/>.
    /// </summary>
    /// <param name="current">The date to be changed.</param>
    /// <param name="days">Number of business days to be subtracted.</param>
    /// <param name="holidays">An optional list of holiday (non-business) days to consider.</param>
    /// <returns>A <see cref="DateTime"/> increased by a given number of business days.</returns>
    public static DateTime SubtractBusinessDays(
        this DateTime current, 
        int days,
        IEnumerable<DateTime> holidays)
    {
        return AddBusinessDays(current, -days, holidays);
    }

    /// <summary>
    /// Retrieves the number of business days from two dates
    /// </summary>
    /// <param name="startDate">The inclusive start date</param>
    /// <param name="endDate">The inclusive end date</param>
    /// <param name="holidays">An optional list of holiday (non-business) days to consider.</param>
    /// <returns></returns>
    public static int GetBusinessDays(
        this DateTime startDate, 
        DateTime endDate,
        IEnumerable<DateTime> holidays)
    {
        if (startDate > endDate)
            throw new NotSupportedException("ERROR: [startDate] cannot be greater than [endDate].");

        int cnt = 0;
        for (var current = startDate; current < endDate; current = current.AddDays(1))
        {
            if (current.DayOfWeek == DayOfWeek.Saturday
                || current.DayOfWeek == DayOfWeek.Sunday
                || (holidays != null && holidays.Contains(current.Date))
                )
            {
                // skip holiday
            }
            else cnt++;
        }
        return cnt;
    }

    /// <summary>
    /// Calculate Easter Sunday for any given year.
    /// src.: https://stackoverflow.com/a/2510411/1233379
    /// </summary>
    /// <param name="year">The year to calcolate Easter against.</param>
    /// <returns>a DateTime object containing the Easter month and day for the given year</returns>
    public static DateTime GetEasterSunday(int year)
    {
        int day = 0;
        int month = 0;

        int g = year % 19;
        int c = year / 100;
        int h = (c - (int)(c / 4) - (int)((8 * c + 13) / 25) + 19 * g + 15) % 30;
        int i = h - (int)(h / 28) * (1 - (int)(h / 28) * (int)(29 / (h + 1)) * (int)((21 - g) / 11));

        day = i - ((year + (int)(year / 4) + i + 2 - c + (int)(c / 4)) % 7) + 28;
        month = 3;

        if (day > 31)
        {
            month++;
            day -= 31;
        }

        return new DateTime(year, month, day);
    }

    /// <summary>
    /// Retrieve holidays for given years
    /// </summary>
    /// <param name="years">an array of years to retrieve the holidays</param>
    /// <param name="countryCode">a country two letter ISO (ex.: "IT") to add the holidays specific for that country</param>
    /// <param name="cityName">a city name to add the holidays specific for that city</param>
    /// <returns></returns>
    public static IEnumerable<DateTime> GetHolidays(IEnumerable<int> years, string countryCode = null, string cityName = null)
    {
        var lst = new List<DateTime>();

        foreach (var year in years.Distinct())
        {
            lst.AddRange(new[] {
                new DateTime(year, 1, 1),       // 1 gennaio (capodanno)
                new DateTime(year, 1, 6),       // 6 gennaio (epifania)
                new DateTime(year, 5, 1),       // 1 maggio (lavoro)
                new DateTime(year, 8, 15),      // 15 agosto (ferragosto)
                new DateTime(year, 11, 1),      // 1 novembre (ognissanti)
                new DateTime(year, 12, 8),      // 8 dicembre (immacolata concezione)
                new DateTime(year, 12, 25),     // 25 dicembre (natale)
                new DateTime(year, 12, 26)      // 26 dicembre (s. stefano)
            });

            // add easter sunday (pasqua) and monday (pasquetta)
            var easterDate = GetEasterSunday(year);
            lst.Add(easterDate);
            lst.Add(easterDate.AddDays(1));

            // country-specific holidays
            if (!String.IsNullOrEmpty(countryCode))
            {
                switch (countryCode.ToUpper())
                {
                    case "IT":
                        lst.Add(new DateTime(year, 4, 25));     // 25 aprile (liberazione)
                        break;
                    case "US":
                        lst.Add(new DateTime(year, 7, 4));     // 4 luglio (Independence Day)
                        break;

                    // todo: add other countries

                    case default:
                        // unsupported country: do nothing
                        break;
                }
            }

            // city-specific holidays
            if (!String.IsNullOrEmpty(cityName))
            {
                switch (cityName)
                {
                    case "Rome":
                    case "Roma":
                        lst.Add(new DateTime(year, 6, 29));  // 29 giugno (s. pietro e paolo)
                        break;
                    case "Milano":
                    case "Milan":
                        lst.Add(new DateTime(year, 12, 7));  // 7 dicembre (s. ambrogio)
                        break;

                    // todo: add other cities

                    default:
                        // unsupported city: do nothing
                        break;

                }
            }
        }
        return lst;
    }
}

使用情報

コードは一目瞭然ですが、使用方法を説明するいくつかの例を以下に示します。

追加の10営業日(土曜日と日曜日の平日のみをスキップ)

var dtResult = DateTimeUtil.AddBusinessDays(srcDate, 10);

10営業日追加します(2019年の土曜日、日曜日、および国に依存しないすべての休日をスキップします)

var dtResult = DateTimeUtil.AddBusinessDays(srcDate, 10, GetHolidays(2019));

10営業日を追加します(土、日、2019年のすべてのイタリアの休日をスキップします)

var dtResult = DateTimeUtil.AddBusinessDays(srcDate, 10, GetHolidays(2019, "IT"));

10営業日を追加します(土曜日、日曜日、イタリアのすべての休日、2019年のローマ固有の休日をスキップします)

var dtResult = DateTimeUtil.AddBusinessDays(srcDate, 10, GetHolidays(2019, "IT", "Rome"));

上記の関数とコード例は、私のブログのこの投稿でさらに説明さています。


0
    public static DateTime AddBusinessDays(DateTime date, int days)
    {
        if (days == 0) return date;
        int i = 0;
        while (i < days)
        {
            if (!(date.DayOfWeek == DayOfWeek.Saturday ||  date.DayOfWeek == DayOfWeek.Sunday)) i++;  
            date = date.AddDays(1);
        }
        return date;
    }

将来的には、答えのためにもう少しコンテキストを追加し、おそらくあなたが持っているものを入れた理由を追加してください:)
dax

0

追加する負の日数をサポートする「AddBusinessDays」が必要でしたが、次のようになりました。

// 0 == Monday, 6 == Sunday
private static int epochDayToDayOfWeek0Based(long epochDay) {
    return (int)Math.floorMod(epochDay + 3, 7);
}

public static int daysBetween(long fromEpochDay, long toEpochDay) {
    // http://stackoverflow.com/questions/1617049/calculate-the-number-of-business-days-between-two-dates
    final int fromDOW = epochDayToDayOfWeek0Based(fromEpochDay);
    final int toDOW = epochDayToDayOfWeek0Based(toEpochDay);
    long calcBusinessDays = ((toEpochDay - fromEpochDay) * 5 + (toDOW - fromDOW) * 2) / 7;

    if (toDOW   == 6) calcBusinessDays -= 1;
    if (fromDOW == 6) calcBusinessDays += 1;
    return (int)calcBusinessDays;
}

public static long addDays(long epochDay, int n) {
    // https://alecpojidaev.wordpress.com/2009/10/29/work-days-calculation-with-c/
    // NB: in .NET, Sunday == 0, but in our code Monday == 0
    final int dow = (epochDayToDayOfWeek0Based(epochDay) + 1) % 7;
    final int wds = n + (dow == 0 ? 1 : dow); // Adjusted number of working days to add, given that we now start from the immediately preceding Sunday
    final int wends = n < 0 ? ((wds - 5) / 5) * 2
                            : (wds / 5) * 2 - (wds % 5 == 0 ? 2 : 0);
    return epochDay - dow + // Find the immediately preceding Sunday
           wds +            // Add computed working days
           wends;           // Add weekends that occur within each complete working week
}

ループは必要ないので、「大きな」追加でもかなり高速でなければなりません。

新しいJDK8 LocalDateクラスによって公開されており、私がJavaで作業していたため、エポックからの暦日数で表される日で動作します。ただし、他の設定に合わせるのは簡単です。

基本的な特性があることですaddDays常にすべてのために平日を返し、ということdndaysBetween(d, addDays(d, n)) == n

理論的には、0日の加算と0日の減算は異なる演算であることに注意してください(日付が日曜日の場合、0日を加算すると月曜日に、0日を減算すると金曜日に移動します)。負の0(浮動小数点以外)のようなものはないため、引数n = 0をゼロ日を追加することを意味すると解釈することを選択しました。


0

これはGetBusinessDaysへのより簡単な方法であると私は信じています:

    public int GetBusinessDays(DateTime start, DateTime end, params DateTime[] bankHolidays)
    {
        int tld = (int)((end - start).TotalDays) + 1; //including end day
        int not_buss_day = 2 * (tld / 7); //Saturday and Sunday
        int rest = tld % 7; //rest.

        if (rest > 0)
        {
            int tmp = (int)start.DayOfWeek - 1 + rest;
            if (tmp == 6 || start.DayOfWeek == DayOfWeek.Sunday) not_buss_day++; else if (tmp > 6) not_buss_day += 2;
        }

        foreach (DateTime bankHoliday in bankHolidays)
        {
            DateTime bh = bankHoliday.Date;
            if (!(bh.DayOfWeek == DayOfWeek.Saturday || bh.DayOfWeek == DayOfWeek.Sunday) && (start <= bh && bh <= end))
            {
                not_buss_day++;
            }
        }
        return tld - not_buss_day;
    }

0

これが、出発日と顧客の配達日の両方を含む私のコードです。

            // Calculate departure date
            TimeSpan DeliveryTime = new TimeSpan(14, 30, 0); 
            TimeSpan now = DateTime.Now.TimeOfDay;
            DateTime dt = DateTime.Now;
            if (dt.TimeOfDay > DeliveryTime) dt = dt.AddDays(1);
            if (dt.DayOfWeek == DayOfWeek.Saturday) dt = dt.AddDays(1);
            if (dt.DayOfWeek == DayOfWeek.Sunday) dt = dt.AddDays(1);
            dt = dt.Date + DeliveryTime;
            string DepartureDay = "today at "+dt.ToString("HH:mm");
            if (dt.Day!=DateTime.Now.Day)
            {
                DepartureDay = dt.ToString("dddd at HH:mm", new CultureInfo(WebContextState.CurrentUICulture));
            }
            Return DepartureDay;

            // Caclulate delivery date
            dt = dt.AddDays(1);
            if (dt.DayOfWeek == DayOfWeek.Saturday) dt = dt.AddDays(1);
            if (dt.DayOfWeek == DayOfWeek.Sunday) dt = dt.AddDays(1);
            string DeliveryDay = dt.ToString("dddd", new CultureInfo(WebContextState.CurrentUICulture));
            return DeliveryDay;

ハッピーコーディング。


0
public static DateTime AddWorkingDays(this DateTime date, int daysToAdd)
{
    while (daysToAdd > 0)
    {
        date = date.AddDays(1);

        if (date.DayOfWeek != DayOfWeek.Saturday && date.DayOfWeek != DayOfWeek.Sunday)
        {
            daysToAdd -= 1;
        }
    }

    return date;
}

0
public static int GetBusinessDays(this DateTime start, DateTime end)
            {
                return Enumerable.Range(0, (end- start).Days)
                                .Select(a => start.AddDays(a))
                                .Where(a => a.DayOfWeek != DayOfWeek.Sunday)
                                .Where(a => a.DayOfWeek != DayOfWeek.Saturday)
                                .Count();
    
            }

-1

これが誰かを助けることを願っています。

private DateTime AddWorkingDays(DateTime addToDate, int numberofDays)
    {
        addToDate= addToDate.AddDays(numberofDays);
        while (addToDate.DayOfWeek == DayOfWeek.Saturday || addToDate.DayOfWeek == DayOfWeek.Sunday)
        {
            addToDate= addToDate.AddDays(1);
        }
        return addToDate;
    }

2
これは誤りです。ほとんどの場合、機能しません。誰を助けることはほとんどありません。
Neolisk 2015年
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.