如何在c#中获得BiWeekly Pay Period?

时间:2014-05-07 00:18:56

标签: c# datetime if-statement

根据今天的日期,我有这个代码来获得第一周的第一天。

CultureInfo defaultCultureInfo = CultureInfo.CurrentCulture;
DayOfWeek firstDay = _culture.DateTimeFormat.FirstDayOfWeek;
DateTime firstDayInWeek = dayInWeek.Date;
while (firstDayInWeek.DayOfWeek != firstDay)
    firstDayInWeek = firstDayInWeek.AddDays(-1);
return firstDayInWeek;

如何在此处返回biweeklyFirstDay

Ex:今天的日期是2014年5月27日。我得到的结果是

firstDayInWeek = 26 May 2014.

但我需要的是2014年5月19日。

简单地说,我想根据系统的今日日期返回5月19日,6月2日,6月16日,6月30日,7月14日,7月28日,8月​​11日。

任何例子都会受到赞赏。

4 个答案:

答案 0 :(得分:2)

你想要这样的东西:

IEnumerable<DateTime> Payday(DateTime startDate, int howMany)
{
    int count = 0, mondays = 0;

    while (count < howMany)
    {
        startDate = startDate.AddDays(1);

        if (startDate.DayOfWeek == DayOfWeek.Monday && mondays == 0)
        {
            mondays++;
        }
        else if (startDate.DayOfWeek == DayOfWeek.Monday)
        {
            mondays = 0;
            count++;
            yield return startDate;
        }
    }
}

当这样调用时:

var payDates = Payday(DateTime.Now, 6);
假设您今天开始工作,

payDates 等于接下来的6个付款日期。

当我在控制台应用程序中使用它时,我得到以下输出:

Output

答案 1 :(得分:2)

使用此代码获取包含firstDayInWeek的周数。

var calendar = System.Threading.Thread.CurrentThread.CurrentCulture.Calendar;

var week = calendar.GetWeekOfYear(firstDayInWeek, CalendarWeekRule.FirstDay, firstDay);

然后将其除以2并查看余数是否为0(表示它是偶数还是奇数周 - 即第18周对比19)。

您指定的日期属于第21周,因此以下代码检测到不能被2整除,并减去7天,为您提供第20周的第一天。

if (currentWeek % 2 != 0)
    firstDayInWeek = firstDayInWeek.AddDays(-7);

答案 2 :(得分:1)

    static void Main(string[] args)
    {
        DayOfWeek firstDayOfWeek = DayOfWeek.Monday;
        DateTime sunday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek);
        DateTime firstDay = sunday.AddDays((int)firstDayOfWeek);
        DateTime value = firstDay;

        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine(value.ToShortDateString());
            value = value.AddDays(14);
        }

    }

答案 3 :(得分:0)

int delta = _culture.DateTimeFormat.FirstDayOfWeek - DateTime.Now.DayOfWeek;
while... // some criterion for continuing your quest for biweekly start days is true
{
    DateTime monday = DateTime.Now.AddDays(delta);
    delta += 14;
    // do something with each biweekly "monday" here
}