날짜를 "11일", "21일" 또는 "23일"(정규 표시기)으로 어떻게 포맷합니까?
는 이것이 그날을 로 줄 있다.11
,21
,23
SimpleDateFormat formatDayOfMonth = new SimpleDateFormat("d");
그러나 순서형 지시자를 포함하도록 날짜를 어떻게 포맷합니까?11th
,21st
★★★★★★★★★★★★★★★★★」23rd
// https://github.com/google/guava
import static com.google.common.base.Preconditions.*;
String getDayOfMonthSuffix(final int n) {
checkArgument(n >= 1 && n <= 31, "illegal day of month: " + n);
if (n >= 11 && n <= 13) {
return "th";
}
switch (n % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
@kalietech의 테이블은 좋지만 같은 정보가 반복되기 때문에 버그가 발생할 가능성이 있습니다.가 실제로 .7tn
,17tn
, , , , 입니다.27tn
(StackOverflow의 유동성이 있기 때문에 시간이 지남에 따라 이 버그는 수정될 수 있으므로 응답의 버전 이력을 확인하여 오류를 확인하십시오).
JDK에는 이 작업을 수행할 수 있는 기능이 없습니다.
static String[] suffixes =
// 0 1 2 3 4 5 6 7 8 9
{ "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th",
// 10 11 12 13 14 15 16 17 18 19
"th", "th", "th", "th", "th", "th", "th", "th", "th", "th",
// 20 21 22 23 24 25 26 27 28 29
"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th",
// 30 31
"th", "st" };
Date date = new Date();
SimpleDateFormat formatDayOfMonth = new SimpleDateFormat("d");
int day = Integer.parseInt(formatDateOfMonth.format(date));
String dayStr = day + suffixes[day];
또는 캘린더 사용:
Calendar c = Calendar.getInstance();
c.setTime(date);
int day = c.get(Calendar.DAY_OF_MONTH);
String dayStr = day + suffixes[day];
@thorbjörn-ravn-andersen의 코멘트에 따라 다음과 같은 표는 현지화할 때 도움이 됩니다.
static String[] suffixes =
{ "0th", "1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th",
"10th", "11th", "12th", "13th", "14th", "15th", "16th", "17th", "18th", "19th",
"20th", "21st", "22nd", "23rd", "24th", "25th", "26th", "27th", "28th", "29th",
"30th", "31st" };
private String getCurrentDateInSpecificFormat(Calendar currentCalDate) {
String dayNumberSuffix = getDayNumberSuffix(currentCalDate.get(Calendar.DAY_OF_MONTH));
DateFormat dateFormat = new SimpleDateFormat(" d'" + dayNumberSuffix + "' MMMM yyyy");
return dateFormat.format(currentCalDate.getTime());
}
private String getDayNumberSuffix(int day) {
if (day >= 11 && day <= 13) {
return "th";
}
switch (day % 10) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
}
하다SimpleDateFormat
8년 전 질문을 받았을 때 수업은 사용해도 괜찮았지만, 오래되었을 뿐만 아니라 귀찮기로 악명 높기 때문에 지금은 피해야 합니다.java.time
★★★★★★ 。
편집
DateTimeFormatterBuilder.appendText(TemporalField, Map<Long, String>)
이 목적에 매우 적합합니다.델은 이를 사용하여 다음과 같은 작업을 수행하는 포메터를 구축합니다.
Map<Long, String> ordinalNumbers = new HashMap<>(42);
ordinalNumbers.put(1L, "1st");
ordinalNumbers.put(2L, "2nd");
ordinalNumbers.put(3L, "3rd");
ordinalNumbers.put(21L, "21st");
ordinalNumbers.put(22L, "22nd");
ordinalNumbers.put(23L, "23rd");
ordinalNumbers.put(31L, "31st");
for (long d = 1; d <= 31; d++) {
ordinalNumbers.putIfAbsent(d, "" + d + "th");
}
DateTimeFormatter dayOfMonthFormatter = new DateTimeFormatterBuilder()
.appendText(ChronoField.DAY_OF_MONTH, ordinalNumbers)
.appendPattern(" MMMM")
.toFormatter();
LocalDate date = LocalDate.of(2018, Month.AUGUST, 30);
for (int i = 0; i < 6; i++) {
System.out.println(date.format(dayOfMonthFormatter));
date = date.plusDays(1);
}
이 스니펫의 출력은 다음과 같습니다.
30th August 31st August 1st September 2nd September 3rd September 4th September
구답
이 코드는 더 짧지만 IMHO는 그리 우아하지 않습니다.
// ordinal indicators by numbers (1-based, cell 0 is wasted)
String[] ordinalIndicators = new String[31 + 1];
Arrays.fill(ordinalIndicators, 1, ordinalIndicators.length, "th");
ordinalIndicators[1] = ordinalIndicators[21] = ordinalIndicators[31] = "st";
ordinalIndicators[2] = ordinalIndicators[22] = "nd";
ordinalIndicators[3] = ordinalIndicators[23] = "rd";
DateTimeFormatter dayOfMonthFormatter = DateTimeFormatter.ofPattern("d");
LocalDate today = LocalDate.now(ZoneId.of("America/Menominee")).plusWeeks(1);
System.out.println(today.format(dayOfMonthFormatter)
+ ordinalIndicators[today.getDayOfMonth()]);
방금 이 토막글을 실행하면서
23일
「 」의 많은 의 1개java.time
요일을 직설적이고 신뢰할 수 있다는 것입니다.int
이는 테이블에서 올바른 서픽스를 선택하기 위해 반드시 필요합니다.
단위 테스트도 써보시길 권합니다.
PS 유사한 포맷터를 사용하여 다음과 같은 서수를 포함하는 날짜 문자열을 해석할 수도 있습니다.1st
,2nd
이 문제는 Java - Parse date with optional seconds로 해결되었습니다.
링크: Oracle 튜토리얼: 사용 방법을 설명하는 날짜 시간java.time
.
질문이 좀 낡았어요.이 질문은 매우 시끄럽기 때문에 정적 방법으로 해결한 것을 util로 게시합니다.복사, 붙여넣기, 사용하세요!
public static String getFormattedDate(Date date){
Calendar cal=Calendar.getInstance();
cal.setTime(date);
//2nd of march 2015
int day=cal.get(Calendar.DATE);
if(!((day>10) && (day<19)))
switch (day % 10) {
case 1:
return new SimpleDateFormat("d'st' 'of' MMMM yyyy").format(date);
case 2:
return new SimpleDateFormat("d'nd' 'of' MMMM yyyy").format(date);
case 3:
return new SimpleDateFormat("d'rd' 'of' MMMM yyyy").format(date);
default:
return new SimpleDateFormat("d'th' 'of' MMMM yyyy").format(date);
}
return new SimpleDateFormat("d'th' 'of' MMMM yyyy").format(date);
}
뿌로즈 테스트용
예: 메인 메서드에서 호출!
Date date = new Date();
Calendar cal=Calendar.getInstance();
cal.setTime(date);
for(int i=0;i<32;i++){
System.out.println(getFormattedDate(cal.getTime()));
cal.set(Calendar.DATE,(cal.getTime().getDate()+1));
}
출력:
22nd of February 2018
23rd of February 2018
24th of February 2018
25th of February 2018
26th of February 2018
27th of February 2018
28th of February 2018
1st of March 2018
2nd of March 2018
3rd of March 2018
4th of March 2018
5th of March 2018
6th of March 2018
7th of March 2018
8th of March 2018
9th of March 2018
10th of March 2018
11th of March 2018
12th of March 2018
13th of March 2018
14th of March 2018
15th of March 2018
16th of March 2018
17th of March 2018
18th of March 2018
19th of March 2018
20th of March 2018
21st of March 2018
22nd of March 2018
23rd of March 2018
24th of March 2018
25th of March 2018
String ordinal(int num)
{
String[] suffix = {"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"};
int m = num % 100;
return String.valueOf(num) + suffix[(m > 3 && m < 21) ? 0 : (m % 10)];
}
만약 당신이 i18n을 인식하려고 한다면 그 해결책은 더욱 복잡해진다.
문제는 다른 언어에서 접미사는 숫자 자체뿐만 아니라 그것이 세는 명사에도 의존할 수 있다는 것이다.예를 들어 러시아어로 '2주째'는 '2주째'이지만 '2주째'는 '2주째'다.이것은 일수만 포맷하는 경우에는 해당되지 않지만, 조금 더 일반적인 경우에는 복잡성에 유의해야 합니다.
(실제로 구현할 시간이 없었습니다) 좋은 해결책은 부모 클래스로 전달하기 전에 SimpleDateFormetter를 확장하여 Locale-aware MessageFormat을 적용하는 것입니다.이렇게 하면 예를 들어 3월 형식 %M은 "3rd", %MM은 "03rd", %MM은 "3rd"를 얻을 수 있습니다.외부에서는 이 클래스가 일반 SimpleDateFormatter처럼 보이지만 더 많은 형식을 지원합니다.또한 이 패턴이 일반 SimpleDateFormetter에 의해 잘못 적용되었을 경우 결과는 잘못된 포맷이지만 읽을 수 있습니다.
이 예의 대부분은 11, 12, 13에서는 동작하지 않습니다.이것은 보다 일반적인 것으로, 모든 경우에 유효합니다.
switch (date) {
case 1:
case 21:
case 31:
return "" + date + "st";
case 2:
case 22:
return "" + date + "nd";
case 3:
case 23:
return "" + date + "rd";
default:
return "" + date + "th";
}
수동 형식에 근거한 영어만의 솔루션을 요구하는 답변에는 만족할 수 없습니다.한동안 적절한 해결책을 찾다가 드디어 찾았어요.
RuleBasedNumber를 사용해야 합니다.형식도 완벽하고 장소도 존중해
RuleBasedNumberFormat
ICU
@Pierre-Olivier Dybman(http://www.icu-project.org/apiref/icu4j/com/ibm/icu/text/RuleBasedNumberFormat.html),에서 ICU 프로젝트 라이브러리 링크에 감사했습니다만, 사용 방법을 알아내야 했기 때문에, 예를 들면,RuleBasedNumberFormat
츠키다
날짜 전체가 아닌 단일 숫자 형식만 지정되므로 형식에서 날짜를 찾는 경우 결합된 문자열을 작성해야 합니다.예를 들어 2월 3일 월요일.
는 '보다 낫다'를 설정합니다.RuleBasedNumberFormat
으로서는, 「」를 합니다.java.time ZonedDateTime
를 사용하여 숫자를 서수로 문자열로 포맷합니다.
RuleBasedNumberFormat numOrdinalFormat = new RuleBasedNumberFormat(Locale.UK,
RuleBasedNumberFormat.ORDINAL);
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Pacific/Auckland"));
String dayNumAndOrdinal = numOrdinalFormat.format(zdt.toLocalDate().getDayOfMonth());
출력 예:
세 번째
또는
넷째
기타.
새로운 java.time 패키지와 새로운 Java 스위치 문을 사용하면 다음 명령어를 해당 월의 날짜에 쉽게 배치할 수 있습니다.한 가지 단점은 DateFormatter 클래스에서 지정된 캔 포맷에 적합하지 않다는 것입니다.
어떤 , 그 날을 포함하면 .%s%s
날짜 및 서수를 나중에 추가합니다.
ZonedDateTime ldt = ZonedDateTime.now();
String format = ldt.format(DateTimeFormatter
.ofPattern("EEEE, MMMM '%s%s,' yyyy hh:mm:ss a zzz"));
이제 요일과 방금 포맷한 날짜를 도우미 메서드로 전달하여 서수를 추가합니다.
int day = ldt.getDayOfMonth();
System.out.println(applyOrdinalDaySuffix(format, day));
인쇄물
Tuesday, October 6th, 2020 11:38:23 AM EDT
도우미 방법은 다음과 같습니다.
「 」의 Java 14
switch 식을 사용하면 서수를 쉽게 얻을 수 있습니다.
public static String applyOrdinalDaySuffix(String format,
int day) {
if (day < 1 || day > 31)
throw new IllegalArgumentException(
String.format("Bad day of month (%s)", day));
String ord = switch (day) {
case 1, 21, 31 -> "st";
case 2, 22 -> "nd";
case 3, 23 -> "rd";
default -> "th";
};
return String.format(format, day, ord);
}
이것을 하는 더 간단하고 확실한 방법이 있다.사용하는 함수는 getDateFromDateString(dateString)입니다.기본적으로 날짜 문자열에서 st/nd/rd/th를 삭제하고 단순히 구문 분석합니다.SimpleDateFormat을 원하는 대로 변경할 수 있습니다.이렇게 하면 동작합니다.
public static final SimpleDateFormat sdf = new SimpleDateFormat("d");
public static final Pattern p = Pattern.compile("([0-9]+)(st|nd|rd|th)");
private static Date getDateFromDateString(String dateString) throws ParseException {
return sdf.parse(deleteOrdinal(dateString));
}
private static String deleteOrdinal(String dateString) {
Matcher m = p.matcher(dateString);
while (m.find()) {
dateString = dateString.replaceAll(Matcher.quoteReplacement(m.group(0)), m.group(1));
}
return dateString;
}
Greg가 제공하는 솔루션의 유일한 문제점은 100보다 큰 숫자와 끝의 "10" 숫자를 고려하지 않는다는 것입니다.예를 들어 111은 111위가 아니라 111위여야 합니다.제 솔루션은 다음과 같습니다.
/**
* Return ordinal suffix (e.g. 'st', 'nd', 'rd', or 'th') for a given number
*
* @param value
* a number
* @return Ordinal suffix for the given number
*/
public static String getOrdinalSuffix( int value )
{
int hunRem = value % 100;
int tenRem = value % 10;
if ( hunRem - tenRem == 10 )
{
return "th";
}
switch ( tenRem )
{
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
}
저는 이 패턴을 얻기 위해 제 자신에게 도우미 방법을 썼습니다.
public static String getPattern(int month) {
String first = "MMMM dd";
String last = ", yyyy";
String pos = (month == 1 || month == 21 || month == 31) ? "'st'" : (month == 2 || month == 22) ? "'nd'" : (month == 3 || month == 23) ? "'rd'" : "'th'";
return first + pos + last;
}
그리고 우리는 그것을 '그것'이라고 부를 수 있다.
LocalDate localDate = LocalDate.now();//For reference
int month = localDate.getDayOfMonth();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(getPattern(month));
String date = localDate.format(formatter);
System.out.println(date);
출력은
December 12th, 2018
아래 기능을 사용해 보십시오.
public static String getFormattedDate(Date date)
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
//2nd of march 2015
int day = cal.get(Calendar.DATE);
if (!((day > 10) && (day < 19)))
switch (day % 10) {
case 1:
return new SimpleDateFormat("d'st' 'of' MMMM yyyy").format(date);
case 2:
return new SimpleDateFormat("d'nd' 'of' MMMM yyyy").format(date);
case 3:
return new SimpleDateFormat("d'rd' 'of' MMMM yyyy").format(date);
default:
return new SimpleDateFormat("d'th' 'of' MMMM yyyy").format(date);
}
return new SimpleDateFormat("d'th' 'of' MMMM yyyy").format(date);
}
다음은 패턴을 발견한 경우 올바른 서픽스 리터럴로 DateTimeFormatter 패턴을 업데이트하는 방법입니다.d'00'
예를 들어, 1개월의 날에 대해서는, 다음과 같이 치환됩니다.d'st'
패턴이 갱신되면 Date Time Formatter로 전송하여 나머지 작업을 수행할 수 있습니다.
private static String[] suffixes = {"th", "st", "nd", "rd"};
private static String updatePatternWithDayOfMonthSuffix(TemporalAccessor temporal, String pattern) {
String newPattern = pattern;
// Check for pattern `d'00'`.
if (pattern.matches(".*[d]'00'.*")) {
int dayOfMonth = temporal.get(ChronoField.DAY_OF_MONTH);
int relevantDigits = dayOfMonth < 30 ? dayOfMonth % 20 : dayOfMonth % 30;
String suffix = suffixes[relevantDigits <= 3 ? relevantDigits : 0];
newPattern = pattern.replaceAll("[d]'00'", "d'" + suffix + "'");
}
return newPattern;
}
포맷 콜 직전에 원래의 패턴을 갱신할 필요가 있습니다.
public static String format(TemporalAccessor temporal, String pattern) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(updatePatternWithDayOfMonthSuffix(temporal, pattern));
return formatter.format(temporal);
}
따라서 서식 패턴이 Java 코드(예: 템플릿) 외부에 정의되어 있는 경우, Java에서 패턴을 정의할 수 있는 경우 @OleV.V.의 답변이 더 적절할 수 있습니다.
public static String getReadableDate(final int date){
String suffix = "th";
switch (date){
case 1:
case 21:
case 31:
suffix = "st";
break;
case 2:
case 22:
suffix = "nd";
break;
case 3:
case 23:
suffix = "rd";
break;
}
return date + suffix;
}
코틀린에서는 이렇게 쓸 수 있어요.
fun changeDateFormats(currentFormat: String, dateString: String): String {
var result = ""
try {
val formatterOld = SimpleDateFormat(currentFormat, Locale.getDefault())
formatterOld.timeZone = TimeZone.getTimeZone("UTC")
var date: Date? = null
date = formatterOld.parse(dateString)
val dayFormate = SimpleDateFormat("d", Locale.getDefault())
var day = dayFormate.format(date)
val formatterNew = SimpleDateFormat("hh:mm a, d'" + getDayOfMonthSuffix(day.toInt()) + "' MMM yy", Locale.getDefault())
if (date != null) {
result = formatterNew.format(date)
}
} catch (e: ParseException) {
e.printStackTrace()
return dateString
}
return result
}
private fun getDayOfMonthSuffix(n: Int): String {
if (n in 11..13) {
return "th"
}
when (n % 10) {
1 -> return "st"
2 -> return "nd"
3 -> return "rd"
else -> return "th"
}
}
이렇게 세팅하다
txt_chat_time_me.text = changeDateFormats("SERVER_DATE", "DATE")
Kotlin을 위해 이걸 써보세요.
fun Int.ordinalAbbrev() =
if (this % 100 / 10 == 1) "th"
else when (this % 10) { 1 -> "st" 2 -> "nd" 3 -> "rd" else -> "th" }
int값을 받아서 이렇게 '3번째' '1번째' '11번째' '2번째'로 돌아옵니다.날짜 형식에도 사용할 수 있습니다.
사용.
fun getFormatedDate(date: String): String {
date.let {
try {
val parser = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
val formatter = SimpleDateFormat("dd MMMM", Locale.getDefault())
val dateArray = formatter.format(parser.parse(it)).split(" ").toTypedArray()
val formatedDate = String.format(
"${dateArray[0]}${
dateArray[0].toInt().ordinalAbbrev()
} ${dateArray[1]}"
)
return formatedDate
} catch (e: Exception) {
e.printStackTrace()
}
}
return date
}
제 대답은 다음과 같습니다.
public String getOrdinal(int day) {
String ordinal;
switch (day % 20) {
case 1:
ordinal = "st";
break;
case 2:
ordinal = "nd";
break;
case 3:
ordinal = "rd";
break;
default:
ordinal = day > 30 > "st" : "th";
}
return ordinal;
}
20으로 모듈로만 하면 모든 날짜에 효과가 있습니다.오늘을 이용하려면LocalDate.now().getDayOfMonth()
과 같은
LocalDate.getDayOfMonth()
다음 방법을 사용하여 전달되는 날짜의 형식 문자열을 가져올 수 있습니다.날짜 형식은 1, 2, 3, 4일입니다.Java에서 SimpleDateFormat 사용(예:- 2015년 9월 1일)
public String getFormattedDate(Date date){
Calendar cal=Calendar.getInstance();
cal.setTime(date);
//2nd of march 2015
int day=cal.get(Calendar.DATE);
switch (day % 10) {
case 1:
return new SimpleDateFormat("d'st' 'of' MMMM yyyy").format(date);
case 2:
return new SimpleDateFormat("d'nd' 'of' MMMM yyyy").format(date);
case 3:
return new SimpleDateFormat("d'rd' 'of' MMMM yyyy").format(date);
default:
return new SimpleDateFormat("d'th' 'of' MMMM yyyy").format(date);
}
다음은 스타일을 하드 코딩하는 것보다 질문에 대한 더 효율적인 대답입니다.
날짜를 서수 번호로 변경하려면 다음 접미사를 사용해야 합니다.
DD + TH = DDTH result >>>> 4TH
OR to spell the number add SP to the format
DD + SPTH = DDSPTH result >>> FOURTH
이 질문에서 나의 완성된 답을 찾아보세요.
public String getDaySuffix(int inDay)
{
String s = String.valueOf(inDay);
if (s.endsWith("1"))
{
return "st";
}
else if (s.endsWith("2"))
{
return "nd";
}
else if (s.endsWith("3"))
{
return "rd";
}
else
{
return "th";
}
}
언급URL : https://stackoverflow.com/questions/4011075/how-do-you-format-the-day-of-the-month-to-say-11th-21st-or-23rd-ordinal
'programing' 카테고리의 다른 글
Vue의 v-for 루프 내에서 항목을 console.log하는 방법 (0) | 2022.08.10 |
---|---|
초기 페이지 로드 시 사용자 가져오기 - Nuxt 미들웨어 (0) | 2022.08.10 |
하위 디렉토리에 VueJS App 배포 (0) | 2022.08.10 |
빈 후 변수를 NULL로 설정 (0) | 2022.08.10 |
Android 룸 지속: AppDatabase_Impl이 없습니다. (0) | 2022.08.10 |