Friday, August 3, 2012

Calendar Basics in asp.net

For all the examples shown below the System.Globalization namespace should be used. It is a class library containing calender related functions.

Get the DayNames in C#.NET
public string[] GetDayNamesList()
{
        DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
        string[] _months = dfi.MonthNames;
        return _months;
}

Output:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Get Week Number of the year.
public static int GetWeekNumber(DateTime dtDate)
    {
        CultureInfo ciCurr = CultureInfo.CurrentCulture;
        int weekNum = ciCurr.Calendar.GetWeekOfYear(dtDate, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);

        return weekNum;
    }

Output:
49

Get weeks spanned by
private static int getWeeksSpannedBy(DateTime startDate, DateTime endDate)
    {
        var calendar = CultureInfo.CurrentCulture.Calendar;
        var weekRule = CultureInfo.CurrentCulture.DateTimeFormat.CalendarWeekRule;
        var firstDayOfWeek = DayOfWeek.Sunday;

        int lastWeek = calendar.GetWeekOfYear(endDate, weekRule, firstDayOfWeek);
        int firstWeek = calendar.GetWeekOfYear(startDate, weekRule, firstDayOfWeek);

        int weekDiff = lastWeek - firstWeek + 1;

        return weekDiff;
    }

Output:
4

No comments:

Codeigniter Shield Authorization

Codeigniter Shield Authorization CodeIgniter Shield is the official authentication and authorization framework for CodeIgniter 4. It provide...