Midhun Mathew
Midhun Mathew

Reputation: 319

Semi-Monthly Date Calculation in C#

I am trying to do calculations on date using "Semi-Monthly". How many days in semi month? AddMonths (0.5) does not work :)

Console.WriteLine("SemiMonthly : " + date.AddMonths(0.5)); //This does not work

Upvotes: 0

Views: 2696

Answers (5)

Max Sorin
Max Sorin

Reputation: 1052

Borrowed some concepts from Tim's answer but the additional logic allows for a schedule to never deviate from the half-month mark. I had noticed that if I ran the function recursively starting from Jan 16 the 24th item was ending up Dec 20-something. I've simplified the function and made it an extension.

public static class DateTimeExtensions
{
    public static DateTime AddHalfMonth(this DateTime dt)
    {
        int daysInMonth = System.DateTime.DaysInMonth(dt.Year, dt.Month);
        if (daysInMonth % 2 == 0 || dt.Day < daysInMonth / 2)
        {
            return dt.AddDays(daysInMonth / 2);
        }

        return dt.AddDays((daysInMonth + 1) / 2);
    }
}

Upvotes: 0

HelloWorld
HelloWorld

Reputation: 1103

If you want, you can add half days of the current month by doing this:

DateTime a = new DateTime();
a.AddDays(DateTime.DaysInMonth(a.Year, a.Month)/2);

Upvotes: 3

James World
James World

Reputation: 29806

You will need to define your own convention for this - there is no canonical notion of a "half month".

Upvotes: 0

Rik
Rik

Reputation: 29243

You're going to have to define what exactly "semi-monthly" means, and in doing so, you'll answer your own question.

For simplicity, I would suggest you just use the first and 15th of each month.

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460340

I guess that adding half of a month means according to this month, then you could do:

public static DateTime AddHalfMonth(DateTime dt, MidpointRounding rounding)
{
    int daysInMonth = System.DateTime.DaysInMonth(dt.Year, dt.Month);
    if(daysInMonth % 2 == 0)
        return dt.AddDays(daysInMonth / 2);
    else if(rounding == MidpointRounding.ToEven)
        return dt.AddDays(daysInMonth / 2);
    else
        return dt.AddDays((daysInMonth + 1) / 2);
}

You can use it in this way:

DateTime inHalfMonth = AddHalfMonth(date, MidpointRounding.ToEven);

Upvotes: 3

Related Questions