[asp.net] how to get current month and year

Can anybody tell me that how I can get current month and year and show it in a label in ASP.NET?

This question is related to asp.net

The answer is


Use the DateTime.Now property. This returns a DateTime object that contains a Year and Month property (both are integers).

string currentMonth = DateTime.Now.Month.ToString();
string currentYear = DateTime.Now.Year.ToString();

monthLabel.Text = currentMonth;
yearLabel.Text = currentYear;

Like this:

DateTime.Now.ToString("MMMM yyyy")

For more information, see DateTime Format Strings.


    public string GetCurrentYear()
    {
        string CurrentYear = DateTime.Now.Year.ToString();

        return CurrentYear;
    }

    public string GetCurrentMonth()
    {
        string CurrentMonth = DateTime.Now.Month.ToString();

        return CurrentMonth;
    }

Find Current Year Using Razor try this

@DateTime.Now.Year

You can use this:

<p>&copy; <%: DateTime.Now.Year %> - My ASP.NET Application</p>

label1.Text = DateTime.Now.Month.ToString();

and

label2.Text = DateTime.Now.Year.ToString();

If you have following two labels:

<asp:Label ID="MonthLabel" runat="server" />
<asp:Label ID="YearLabel" runat="server" />

Than you can use following code just need to set the Text Property for these labels like:

MonthLabel.Text = DateTime.Now.Month.ToString();
YearLabel.Text = DateTime.Now.Year.ToString();

using System.Globalization;

LblMonth.Text = DateTime.Now.Month.ToString();

DateTimeFormatInfo dinfo = new DateTimeFormatInfo();
int month = Convert.ToInt16(LblMonth.Text);

LblMonth.Text = dinfo.GetMonthName(month);