문자열로 된 월 이름
예를 들어 "May", "September", "November"와 같이 월 이름을 문자열로 반환하려고합니다.
나는 시도했다 :
int month = c.get(Calendar.MONTH);
그러나 이것은 정수 (각각 5, 9, 11)를 리턴합니다. 월 이름은 어떻게 알 수 있습니까?
getDisplayName을 사용하십시오 .
이전 API 사용 String.format(Locale.US,"%tB",c);
이것을 사용하십시오 :
Calendar cal=Calendar.getInstance();
SimpleDateFormat month_date = new SimpleDateFormat("MMMM");
String month_name = month_date.format(cal.getTime());
월 이름에는 전체 월 이름이 포함됩니다. 짧은 월 이름을 원하면이 이름을 사용하십시오.
SimpleDateFormat month_date = new SimpleDateFormat("MMM");
String month_name = month_date.format(cal.getTime());
문자열 변수에서 월을 얻으려면 아래 코드를 사용하십시오.
예를 들어 9 월은 다음과 같습니다.
M-> 9
MM-> 09
MMM-> 9 월
MMMM-> 9 월
String monthname=(String)android.text.format.DateFormat.format("MMMM", new Date())
"MMMM"은 확실히 올바른 솔루션이 아닙니다 (많은 언어에서 작동하더라도). "LLLL"패턴을 SimpleDateFormat
독립형 월 이름에 대한 ICU 호환 확장으로서 'L'에 대한 지원이 2010 년 6 월 Android 플랫폼에 추가되었습니다 .
영어로 'MMMM'과 'LLLL'로 인코딩하는 데 차이가 없더라도 다른 언어도 생각해야합니다.
예 Calendar.getDisplayName
를 들어 러시아어로 1 월에 "MMMM"패턴을 사용하면 다음과 같은 결과를 얻을 수 있습니다 Locale
.
января (전체 날짜 문자열 : " 10 января, 2014 ")
그러나 독립형 월 이름의 경우 다음과 같이 예상됩니다.
январь
올바른 솔루션은 다음과 같습니다.
SimpleDateFormat dateFormat = new SimpleDateFormat( "LLLL", Locale.getDefault() );
dateFormat.format( date );
모든 번역의 출처에 관심이있는 경우 여기 에 그레고리력 번역에 대한 참조 가 있습니다 (페이지 상단에 링크 된 다른 캘린더).
이렇게 간단합니다
mCalendar = Calendar.getInstance();
String month = mCalendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
다른 경우에 유용한이 답변을 유지하지만 @trutheality 답변이 가장 간단하고 직접적인 방법 인 것 같습니다.
DateFormatSymbols 를 사용할 수 있습니다.
DateFormatSymbols(Locale.FRENCH).getMonths()[month]; // FRENCH as an example
Android에서 우크라이나어, 러시아어, 체코 어와 같은 언어에 대해 올바른 형식의 표준 월 이름을 얻는 유일한 방법
private String getMonthName(Calendar calendar, boolean short) {
int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_MONTH_DAY | DateUtils.FORMAT_NO_YEAR;
if (short) {
flags |= DateUtils.FORMAT_ABBREV_MONTH;
}
return DateUtils.formatDateTime(getContext(), calendar.getTimeInMillis(), flags);
}
API 15-25에서 테스트 됨
의 출력 월 입니다 Май 하지만 Мая
Calendar
객체 를 사용하는 것이 좋으며 Locale
언어마다 월 이름이 다르기 때문에
// index can be 0 - 11
private String getMonthName(final int index, final Locale locale, final boolean shortName)
{
String format = "%tB";
if (shortName)
format = "%tb";
Calendar calendar = Calendar.getInstance(locale);
calendar.set(Calendar.MONTH, index);
calendar.set(Calendar.DAY_OF_MONTH, 1);
return String.format(locale, format, calendar);
}
전체 월 이름의 예 :
System.out.println(getMonthName(0, Locale.US, false));
결과: January
짧은 월 이름의 예 :
System.out.println(getMonthName(0, Locale.US, true));
결과: Jan
"2018 Nov 01 16:18:22"형식으로 날짜와 시간을 가져 오는 샘플 방법은 다음을 사용합니다.
DateFormat dateFormat = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");
Date date = new Date();
dateFormat.format(date);
독립형 월 이름을 얻는 것은 자바에서 "올바르게"수행하기가 놀랍도록 어렵습니다. (적어도이 글을 쓰는 시점에서. 저는 현재 Java 8을 사용하고 있습니다).
The problem is that in some languages, including Russian and Czech, the standalone version of the month name is different from the "formatting" version. Also, it appears that no single Java API will just give you the "best" string. The majority of answers posted here so far only offer the formatting version. Pasted below is a working solution for getting the standalone version of a single month name, or getting an array with all of them.
I hope this saves someone else some time!
/**
* getStandaloneMonthName, This returns a standalone month name for the specified month, in the
* specified locale. In some languages, including Russian and Czech, the standalone version of
* the month name is different from the version of the month name you would use as part of a
* full date. (Different from the formatting version).
*
* This tries to get the standalone version first. If no mapping is found for a standalone
* version (Presumably because the supplied language has no standalone version), then this will
* return the formatting version of the month name.
*/
private static String getStandaloneMonthName(Month month, Locale locale, boolean capitalize) {
// Attempt to get the standalone version of the month name.
String monthName = month.getDisplayName(TextStyle.FULL_STANDALONE, locale);
String monthNumber = "" + month.getValue();
// If no mapping was found, then get the formatting version of the month name.
if (monthName.equals(monthNumber)) {
DateFormatSymbols dateSymbols = DateFormatSymbols.getInstance(locale);
monthName = dateSymbols.getMonths()[month.getValue()];
}
// If needed, capitalize the month name.
if ((capitalize) && (monthName != null) && (monthName.length() > 0)) {
monthName = monthName.substring(0, 1).toUpperCase(locale) + monthName.substring(1);
}
return monthName;
}
/**
* getStandaloneMonthNames, This returns an array with the standalone version of the full month
* names.
*/
private static String[] getStandaloneMonthNames(Locale locale, boolean capitalize) {
Month[] monthEnums = Month.values();
ArrayList<String> monthNamesArrayList = new ArrayList<>();
for (Month monthEnum : monthEnums) {
monthNamesArrayList.add(getStandaloneMonthName(monthEnum, locale, capitalize));
}
// Convert the arraylist to a string array, and return the array.
String[] monthNames = monthNamesArrayList.toArray(new String[]{});
return monthNames;
}
참고URL : https://stackoverflow.com/questions/6192781/month-name-as-a-string
'code' 카테고리의 다른 글
오류 : 모듈에서 예기치 않은 값 '정의되지 않음'을 가져 왔습니다. (0) | 2020.10.15 |
---|---|
IOS Swift 앱에서 탭 표시 줄 숨기기 (0) | 2020.10.15 |
Android Studio v 1.1 / 1.2의 렌더링 문제 (0) | 2020.10.15 |
Android Studio에서 서명 된 APK의 키 별칭 및 키 비밀번호를 검색하는 방법 (Eclipse에서 마이그레이션 됨) (0) | 2020.10.15 |
프로덕션 엔터프라이즈 환경에서 지금까지 본 것 중 가장 사악한 코드는 무엇입니까? (0) | 2020.10.15 |