모든 달 이름을 나열하는 방법 (예 : 콤보)?
지금은 매월를 만들고 DateTime해당 월만 포함하도록 서식을 지정하고 있습니다.
이것을 수행하는 다른 또는 더 나은 방법이 있습니까?
를 사용하여 DateTimeFormatInfo해당 정보를 얻을 수 있습니다 .
// Will return January
string name = DateTimeFormatInfo.CurrentInfo.GetMonthName(1);
또는 모든 이름을 얻으려면 :
string[] names = DateTimeFormatInfo.CurrentInfo.MonthNames;
with를 DateTimeFormatInfo기반으로 new 를 인스턴스화 하거나 현재 문화권의 속성을 사용할 수도 있습니다 .CultureInfoDateTimeFormatInfo.GetInstanceCultureInfo.DateTimeFormat
var dateFormatInfo = CultureInfo.GetCultureInfo("en-GB").DateTimeFormat;
.Net의 캘린더는 최대 13 개월을 지원하므로 12 개월 만있는 캘린더 (예 : en-US 또는 fr에있는 캘린더)의 경우 끝에 빈 문자열이 추가로 표시됩니다.
이 방법을 사용하면 개월의 키 값 쌍 목록을 int 대응 항목에 적용 할 수 있습니다. Enumerable Ranges 및 LINQ를 사용하여 한 줄로 생성합니다. 만세, LINQ 코드 골프!
var months = Enumerable.Range(1, 12).Select(i => new { I = i, M = DateTimeFormatInfo.CurrentInfo.GetMonthName(i) });
ASP 드롭 다운 목록에 적용하려면 :
// <asp:DropDownList runat="server" ID="ddlMonths" />
ddlMonths.DataSource = months;
ddlMonths.DataTextField = "M";
ddlMonths.DataValueField = "I";
ddlMonths.DataBind();
다음을 사용하여 월 이름이 포함 된 문자열 배열을 반환 할 수 있습니다.
System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
그들은 세계화 네임 스페이스에서 배열로 정의됩니다.
using System.Globalization;
for (int i = 0; i < 12; i++) {
Console.WriteLine(CultureInfo.CurrentUICulture.DateTimeFormat.MonthNames[i]);
}
월 이름을 열거 해보십시오.
for( int i = 1; i <= 12; i++ ){
combo.Items.Add(CultureInfo.CurrentCulture.DateTimeFormat.MonthNames[i]);
}
System.Globalization 네임 스페이스에 있습니다.
도움이 되었기를 바랍니다.
에서 현지화 된 월 Thread.CurrentThread.CurrentCulture.DateTimeFormat.MonthNames및 고정 월 목록을 가져올 수 있습니다 DateTimeFormatInfo.InvariantInfo.MonthNames.
string[] localizedMonths = Thread.CurrentThread.CurrentCulture.DateTimeFormat.MonthNames;
string[] invariantMonths = DateTimeFormatInfo.InvariantInfo.MonthNames;
for( int month = 0; month < 12; month++ )
{
ListItem monthListItem = new ListItem( localizedMonths[month], invariantMonths[month] );
monthsDropDown.Items.Add( monthListItem );
}
달력 유형에 따라 1 년의 개월 수에 문제가있을 수 있지만이 예에서는 12 개월을 가정했습니다.
public IEnumerable<SelectListItem> Months
{
get
{
return Enumerable.Range(1, 12).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = DateTimeFormatInfo.CurrentInfo.GetMonthName(x)
});
}
}
방법은 검색하는 역동적 인 문화 의 달 이름의 특정 목록 의 C # 과 LINQ를 .
ComboBoxName.ItemsSource=
System.Globalization.CultureInfo.
CurrentCulture.DateTimeFormat.MonthNames.
TakeWhile(m => m != String.Empty).ToList();
또는
이 예제에서 익명 개체는 Month 및 MonthName 속성을 사용하여 생성됩니다.
var months = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
.TakeWhile(m => m != String.Empty)
.Select((m,i) => new
{
Month = i+1,
MonthName = m
})
.ToList();
추신 : MonthNames 배열에 빈 13 번째 달이 포함되어 있기 때문에 TakeWhile 메서드를 사용합니다.
아름답게 간결하기 때문에 약간의 LINQ :
var monthOptions = DateTimeFormatInfo.CurrentInfo.MonthNames
.Where(p=>!string.IsNullOrEmpty(p))
.Select((item, index) => new { Id = index + 1, Name = item });
달력이 13 번째 달 이름 (영어로 비어 있음)을 반환하므로 Where 절이 필요합니다.
인덱스는 IEnumerable 내의 인덱스를 반환하므로 실제 월 인덱스에는 +1이 필요합니다.
물론입니다. 10 년 이상 된 질문에 대한 의견을 제공하겠습니다.
필자의 경우 다음 코드로 생성 된 사전 (또는 이와 유사한)을 반환하는 속성을 만듭니다.
Dictionary<int, string> Months = Enumerable.Range(1, 12).Select(i => new KeyValuePair<int, string>(i, System.Globalization.DateTimeFormatInfo.CurrentInfo.GetMonthName(i))).ToDictionary(x => x.Key, x => x.Value);
출력 (Linqpad에서) :
Key Value
1 January
2 February
3 March
4 April
5 May
6 June
7 July
8 August
9 September
10 October
11 November
12 December
누군가가 유용하다고 생각하기를 바랍니다!
나는 다음과 같은 방식으로했다 : (문화를 설정하는 것이 가능하다)
var months = Enumerable.Range(1, 12).Select(i =>
new
{
Index = i,
MonthName = new CultureInfo("en-US").DateTimeFormat.GetAbbreviatedMonthName(i)
})
.ToDictionary(x => x.Index, x => x.MonthName);
List<string> mnt = new List<string>();
int monthCount = Convert.ToInt32(cbYear.Text) == DateTime.Now.Year ? DateTime.Now.Month : 12;
for (int i = 0; i < monthCount; i++)
{
mnt.Add(CultureInfo.CurrentUICulture.DateTimeFormat.MonthNames[i]);
}
cbMonth.DataSource = mnt;
string[] monthNames = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;
foreach (string m in monthNames) // writing out
{
Console.WriteLine(m);
}
산출:
January
February
March
April
May
June
July
August
September
October
November
December
업데이트 : 다른 로케일 / 문화의 경우 출력이 영어로 표시되지 않을 수 있습니다. 그래도 전에 테스트하지 않았습니다.
미국 영어 만 해당 :
string[] monthNames = (new System.Globalization.CultureInfo("en-US")).DateTimeFormat.MonthNames;
Here is a good example for filling a drop down list with Months for Credit Card form:
Dim currentCulture As CultureInfo = CultureInfo.CurrentUICulture
Dim monthName, monthNumber As String
For x As Integer = 0 To 11
monthNumber = (x + 1).ToString("D2")
monthName = currentCulture.DateTimeFormat.MonthNames(x)
Dim month As New ListItem(String.Format("{0} - {1}", monthNumber, monthName),
x.ToString("D2"))
ddl_expirymonth.Items.Add(month)
Next
Creates the following localized to current language, example:
01 - January
02 - February
etc.
How to create a custom list of month names in any order
Yes, I'm answering a question from over 10 years ago! :D
Yet, I wanted to add this code snippet on the chance it might help others. It shows how to output a list of month names in any custom order. In my case I needed it to start in October, but you could put the months in any sequence (even have repeating months) by setting the list of integers.
model.Controls = new
{
FiscalMonths = new
{
Value = DateTime.Now.Month,
Options = (new List<int> { 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9 }).Select(p => new
{
Value = p,
Text = DateTimeFormatInfo.CurrentInfo.GetMonthName(p)
})
}
};
And the json output for use in a dropdown:
"FiscalMonths": {
"Value": 10,
"Options": [
{
"Value": 10,
"Text": "October"
},
{
"Value": 11,
"Text": "November"
},
{
"Value": 12,
"Text": "December"
},
{
"Value": 1,
"Text": "January"
},
{
"Value": 2,
"Text": "February"
},
etc ....
참고URL : https://stackoverflow.com/questions/315301/how-to-list-all-month-names-e-g-for-a-combo
'developer tip' 카테고리의 다른 글
| 와일드 카드를 사용하여 PostgreSQL에서 여러 테이블을 삭제하는 방법 (0) | 2020.11.07 |
|---|---|
| 'data : font / woff…'글꼴로드를 거부하면 다음 콘텐츠 보안 정책 지침을 위반합니다.“default-src 'self'”. (0) | 2020.11.06 |
| Android에서 다운로드 폴더에 액세스하는 방법은 무엇입니까? (0) | 2020.11.06 |
| 오류 : 프로세스 ID 0에 연결하지 못했습니다. (0) | 2020.11.06 |
| C에서 함수 호출 재정의 (0) | 2020.11.06 |