如何查找月份和年份 [英] How to find month and year

查看:132
本文介绍了如何查找月份和年份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想显示最近5年(每月)的下拉列表.

下拉菜单中的格式应显示为"Monary-Year"(我想要最近5年的值).

Hi,

I want to display last 5 years(Month-Year) in dropdown.

The format in the dropdown should display "Month-Year" (I want last 5 years values).

推荐答案

使用以下代码

Use the below Code

for (int innlop = 1; innlop <= 5; innlop++)
               DropDownList1.Items.Add(DateTime.Now.AddYears(innlop * -1).Year.ToString());




***




***



我希望直接为每个月创建DateTime对象,而不是直接存储月份和年份.填充下拉列表后,可以根据需要设置日期时间的格式,但也可以存储实际的日期时间对象以供以后使用,并避免对下拉菜单中的文本进行解释.例如,考虑以下内容:
Instead of storing directly the month and the year, I''d prefer creating DateTime objects for each month. When the dropdown is filled the datetime could be formatted as needed but also the actual datetime object could be stored for later use and to avoid interpretation of the text in the dropdown. For example consider this:
System.DateTime dtNow = new DateTime(System.DateTime.Now.Year, System.DateTime.Now.Month, 1);
while (dtNow >= System.DateTime.Now.AddYears(-5)) {
   dtNow.ToString("MMMM-yyyy"); // this would go to the dropdown as DataTextField
   dtNow; //This would go to the dropdown as a DataValueField
   dtNow = dtNow.AddMonths(-1);
}


尝试一下,

Try this,

int yr = 2012;
        string[] monthNames = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
        for (int cnt = yr - 5; cnt < yr; cnt++)
        {
            for (int mth = 0; mth <= 11; mth++)
            {
                ddl_Years.Items.Add(monthNames[mth] + "-" + cnt.ToString());
            }
        }
        ddl_Years.Items.Insert(0, new ListItem("--Please Select--", "0"));


这篇关于如何查找月份和年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆