Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check business days in c#

Tags:

c#

.net

.net-3.5

My client gave me very diffrent requirement yesterday.

I have one folder at server where thousands of files are comming daily. He want me to write a logic to check dates of file. If files are there in folder from more than 3 business days (Mon to Friday) then he want me to delete those files

Example : If any file created in folder on Saturday then that file should delete on wednesday because inbetween we have Saturday and Sunday that should not count as business days.

My developemnt enviornment is c# .NET 3.5

I thought i should write custom method.

Please help me.

like image 570
Hemant Kothiyal Avatar asked Dec 04 '22 06:12

Hemant Kothiyal


1 Answers

George Duckett solution is the one for you.
Just to help you I post an example:

public static class DateExtensions
{
    public static bool IsBusinessDay(this DateTime date)
    {
        return
            date.DayOfWeek != DayOfWeek.Saturday &&
            date.DayOfWeek != DayOfWeek.Sunday;
    }
    public static int BusinessDaysTo(this DateTime fromDate, DateTime toDate, 
                                     int maxAllowed = 0)
    {
        int ret = 0;
        DateTime dt = fromDate;
        while (dt < toDate)
        {
            if (dt.IsBusinessDay()) ret++;
            if (maxAllowed > 0 && ret == maxAllowed) return ret;
            dt = dt.AddDays(1);
        }
        return ret;
    }
}

With this you can do something like this:

DateTime from = DateTime.Now.AddDays(-8);
int ret = from.BusinessDaysTo(DateTime.Now);
int ret2 = from.BusinessDaysTo(DateTime.Now.AddDays(5), 8);
like image 162
Marco Avatar answered Dec 20 '22 15:12

Marco