Monday, 30 September 2013

Date function in c#

List the First Monday of every month using C# 

Here’s some code for listing down the first Monday of every month in an year using C# .NET. The Monday’s listed in this example are for the year 2010

public static void Main(string[] args)
{
    for (int mth = 1; mth <= 12; mth++)
    {
        DateTime dt = new DateTime(2010, mth, 1);
        while (dt.DayOfWeek != DayOfWeek.Monday)
        {
            dt = dt.AddDays(1);
        }
        Console.WriteLine(dt.ToLongDateString());
    }
    Console.ReadLine();
}

Calculate the Monday in the first week of the year

private DateTime GetFirstMondayOfYear(int year)
{
    DateTime dt = new DateTime(year, 1, 1);

    while (dt.DayOfWeek != DayOfWeek.Monday)
    {
        dt = dt.AddDays(1);
    }

    return dt;
}

Calculate week of month in .NET

There is no built in way to do this but here is an extension method that should do the job for you:

static class DateTimeExtensions {
    static GregorianCalendar _gc = new GregorianCalendar();
    public static int GetWeekOfMonth(this DateTime time) {
        DateTime first = new DateTime(time.Year, time.Month, 1);
        return time.GetWeekOfYear() - first.GetWeekOfYear() + 1;
    }

    static int GetWeekOfYear(this DateTime time) {
        return _gc.GetWeekOfYear(time, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
    }
}
Usage:
DateTime time = new DateTime(2010, 1, 25);
Console.WriteLine(time.GetWeekOfMonth());

1 comment:

  1. Faster way for getting the day of week : http://stackoverflow.com/a/22278311/3315914

    ReplyDelete