Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get previous work day [closed]

Tags:

c#

datetime

I need to get previous work day:

public DateTime GetPreviousWorkDay(DateTime date)
{
    DateTime prevDay = date.AddDays(-1);
    bool isHoliday = IsHoliday(prevDay);
    while (isHoliday || prevDay.DayOfWeek == DayOfWeek.Saturday || prevDay.DayOfWeek == DayOfWeek.Sunday)
    {
        prevDay = prevDay.AddDays(-1);
        isHoliday = IsHoliday(prevDay);
    }
    return prevDay;
}

Is this method safe? Can it be an infinite cycle? Is there an simpler way?

like image 319
Olena Avatar asked Oct 03 '13 14:10

Olena


People also ask

How do I find previous business days?

The previous business day is the most recent prior day on which banks were open for business. Business days are Monday through Friday, not including holidays. For example, on a Tuesday, you would see Monday's transactions. On a Monday, you would see the previous Friday's transactions.

How do you get the next business day in Python?

Use the import numpy as np statement to import the numpy module in your Python file. Create a start date and end date using the datetime. date() class of a datetime module. The busday_count() function counts the number of business days between the start date and end date, not including the day of the end dates.

How do I use weekday function in Python?

isoweekday() to get a weekday of a given date in Python Use the isoweekday() method to get the day of the week as an integer, where Monday is 1 and Sunday is 7. i.e., To start from the weekday number from 1, we can use isoweekday() in place of weekday() . The output is 1, which is equivalent to Monday as Monday is 1.


1 Answers

To make logic more clear, I'd extracted IsWeekend method and removed unnecessary temp variables. Simple do..while loop will do the job:

public DateTime PreviousWorkDay(DateTime date)
{
    do 
    {        
        date = date.AddDays(-1);        
    } 
    while(IsHoliday(date) || IsWeekend(date));

    return date;
}

private bool IsWeekend(DateTime date)
{
    return date.DayOfWeek == DayOfWeek.Saturday ||
           date.DayOfWeek == DayOfWeek.Sunday;
}   
like image 76
Sergey Berezovskiy Avatar answered Oct 10 '22 02:10

Sergey Berezovskiy