모든 월 이름을 나열하는 방법(예: 콤보)?
제가 지금 만들고 있는 것은DateTime각 월에 대해 월만 포함하도록 형식을 지정합니다.
이것을 할 수 있는 다른 방법이나 더 나은 방법이 있습니까?
를 사용하여 해당 정보를 가져올 수 있습니다.
// Will return January
string name = DateTimeFormatInfo.CurrentInfo.GetMonthName(1);
또는 모든 이름을 가져옵니다.
string[] names = DateTimeFormatInfo.CurrentInfo.MonthNames;
새 항목을 인스턴스화할 수도 있습니다.DateTimeFormatInfo에 의거하여CultureInfo현재 문화의 속성을 사용하거나 사용할 수 있습니다.
var dateFormatInfo = CultureInfo.GetCultureInfo("en-GB").DateTimeFormat;
의 달력에 유의하십시오.최대 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]);
}
시스템에 있습니다.글로벌화 네임스페이스입니다.
도움이 되길 바랍니다!
public IEnumerable<SelectListItem> Months
{
get
{
return Enumerable.Range(1, 12).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = DateTimeFormatInfo.CurrentInfo.GetMonthName(x)
});
}
}
아주 간결하기 때문에 약간의 LINQ:
var monthOptions = DateTimeFormatInfo.CurrentInfo.MonthNames
.Where(p=>!string.IsNullOrEmpty(p))
.Select((item, index) => new { Id = index + 1, Name = item });
달력이 13번째 달 이름을 반환하기 때문에 Where 절이 필요합니다(영어로는 비어 있음).
인덱스는 IE 숫자 내에서 인덱스를 반환하므로 실제 월 인덱스에 대해 +1이 필요합니다.
다음 날짜에서 현지화된 월 목록을 얻을 수 있습니다.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 );
}
달력 유형에 따라 한 해의 월 수에 약간의 문제가 있을 수 있지만 이 예에서는 12개월로 가정했습니다.
물론입니다. 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
누군가가 이것을 유용하게 찾기를 바랍니다!
LINQ를 사용하여 C#에서 동적 문화별 월 이름 목록을 검색하는 방법.
ComboBoxName.ItemsSource=
System.Globalization.CultureInfo.
CurrentCulture.DateTimeFormat.MonthNames.
TakeWhile(m => m != String.Empty).ToList();
OR
이 예에서는 Month and MonthName 속성을 사용하여 익명 개체가 생성됩니다.
var months = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
.TakeWhile(m => m != String.Empty)
.Select((m,i) => new
{
Month = i+1,
MonthName = m
})
.ToList();
PS: MonthNames 배열에 빈 13번째 달이 포함되어 있기 때문에 TakeWhile 메서드를 사용합니다.
저는 다음과 같은 방법으로 했습니다. (문화 설정이 가능합니다.)
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;
다음은 Months for Credit Card 양식으로 드롭다운 목록을 채우는 좋은 예입니다.
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
현재 언어에 맞게 현지화된 다음을 만듭니다. 예:
01 - January
02 - February
etc.
임의의 순서로 월 이름의 사용자 정의 목록을 만드는 방법
네, 저는 10년 이상 전의 질문에 답하고 있습니다! :d
하지만, 저는 다른 사람들에게 도움이 될 수도 있는 이 코드 조각을 추가하고 싶었습니다.월 이름 목록을 사용자 지정 순서로 출력하는 방법을 보여줍니다.저의 경우 10월에 시작하기 위해 필요했지만 정수 목록을 설정하여 달을 임의의 순서(반복되는 달도 있음)에 넣을 수 있습니다.
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)
})
}
};
드롭다운에 사용할 json 출력:
"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 ....
당신은 아래와 같은 일을 linq로 쉽게 할 수 있어서 당신의 드롭다운에 12개의 아이템만 있을 수 있습니다.
var Months = new SelectList((DateTimeFormatInfo.CurrentInfo.MonthNames).Take(12));
언급URL : https://stackoverflow.com/questions/315301/how-to-list-all-month-names-e-g-for-a-combo
'programing' 카테고리의 다른 글
| 비트 필드가 있는 구조물의 크기는 어떻게 결정/측정됩니까? (0) | 2023.06.11 |
|---|---|
| 개체를 배열로 변환하는 유형 스크립트 - *ngFor는 개체 반복을 지원하지 않기 때문입니다. (0) | 2023.06.11 |
| ID 집합으로 여러 문서를 업데이트합니다.몽구스 (0) | 2023.06.11 |
| 최대 절전 모드에서 Oracle XMLType 열 사용 (0) | 2023.06.11 |
| 왜 'eval'을 사용하는 것이 나쁜 관행입니까? (0) | 2023.06.06 |