C#.NET: 4 payroll/calendar date calculations

csharp.netWhat was last Monday’s date? What is next Friday’s date? Even better, what was the date for the first Monday of last March? What date is the last Friday of this year?

I’ve seen some wacky things done to calculate these types of dates before, most often for payroll or calendar applications. I see people use ginormous switch statements or if/elseif/else blocks for these types of things, with one for each day of the week, or, worse, with functions for leap years and everything!

You don’t need to do that in .NET. DateTime is your friend. Here are 4 examples (using Console for simplicity in demonstration) using C Sharp (C#). You can set the “today” date to anything you want to test, or to use some other date for the calculations.


using System;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime today = DateTime.Now;
            // today = DateTime.Parse("12/31/2008"); // uncomment this to set it to a specific date

            // last Monday’s date was…
            DateTime prevMonday = today.AddDays((int)DayOfWeek.Monday - (int)today.DayOfWeek);
            Console.WriteLine(String.Format("last Monday was {0}", prevMonday.ToShortDateString()));

            // next Friday’s date will be…
            DateTime nextFriday = today.AddDays((int)DayOfWeek.Friday - (int)today.DayOfWeek);
            Console.WriteLine(String.Format("next Friday is {0}", nextFriday.ToShortDateString()));

            // first monday of this month is/was…
            DateTime firstOfMonth = new DateTime(today.Year, today.Month, 1);
            DateTime firstMonday = firstOfMonth.AddDays((int)DayOfWeek.Monday - (int)firstOfMonth.DayOfWeek);
            if (firstMonday < firstOfMonth) firstMonday = firstMonday.AddDays(7);
            Console.WriteLine(String.Format("first monday is/was {0}", firstMonday.ToShortDateString()));

            // last Friday of this month will be…
            int daysInThisMonth = DateTime.DaysInMonth(today.Year, today.Month);
            DateTime lastOfMonth = new DateTime(today.Year, today.Month, daysInThisMonth);
            DateTime lastFriday = lastOfMonth.AddDays((int)DayOfWeek.Friday - (int)lastOfMonth.DayOfWeek);

            if (lastFriday > lastOfMonth) lastFriday = lastFriday.AddDays(-7);
            Console.WriteLine(String.Format("last friday is/was {0}", lastFriday.ToShortDateString()));

            Console.Read();
        }
    }
}

Tags: , , , , ,

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

12 Responses to “C#.NET: 4 payroll/calendar date calculations”

  1. kpg123 says:

    Hi,
    I want to find all the mondays in a month using aps.net with c#,please provide me an exmple

  2. kaeli says:

    I’ll give you the algorithm to find them.

    set var tmpDate = first monday of month
    set var tmpDate2 = first monday of the next month
    while tmpDate < tmpDate2
    add 7 days to tmpDate to get the next monday
    end while

  3. Jordan says:

    And I liked, will be looking at your site.

  4. Srini says:

    Hey Kaeli,

    Really fantastic stuff. Solved my problem in just few mins… great, many thanks…

  5. Mahhoura says:

    Thank you for your work … it saves me a lot of time :D

  6. [...] posts:  C#.NET: 4 payroll/calendar date calculations Fun with [...]

  7. Anthony says:

    I like this article, however, I think something is missing.

    Your calculation for “last Monday’s date” doesn’t see to be last Monday at all, but rather Monday of this week. What if the current day was Sunday?

    prevMonday = today.AddDays(DayOfWeek.Monday – today.DayOfWeek)
    = today.AddDays(1 – 0)
    = today.AddDays(1)

    Ends up adding a day. True, it is a Monday, but not the previous Monday. I’m trying to find the last date of any given DayOfWeek, given any DateTime. I think you’d have to check if dayOfWeek > refDate.DayOfWeek, and if so, subtract an extra 7 days.

    I haven’t tested with this fully, and I’d be interested to see a more elegant solution than what I mentioned.

  8. kaeli says:

    @Anthony – yes, you’re right. I missed that, thank you for pointing that out!

  9. Anthony says:

    Glad I could help. The post helped me quite a bit, so I felt indebted :D

  10. batuqe says:

    Hi, i have some query regarding datetime.

    i want to calculate date of first sunday of november, and i have only todays date so what i have to do for that..
    plz try to help me..
    thank you

  11. goth_ddr says:

    DateTime today
    today = dateTimePicker1.Value;
    int offSet = DayOfWeek.Monday – today.DayOfWeek;
    if (offSet == 0) // it is monday
    {
    DateTime nextMon = today.AddDays( 7);

    }
    else
    {
    DateTime nextMon = today.AddDays((7 + offSet)%7);

    }

  12. sumanth5152 says:

    Thanks for your post.
    It helped me a lot

Leave a Reply