Programming

달력이 잘못된 달을 반환 함

procodes 2020. 8. 24. 21:16
반응형

달력이 잘못된 달을 반환 함


Calendar rightNow = Calendar.getInstance();
String month = String.valueOf(rightNow.get(Calendar.MONTH));

위의 스 니펫을 실행 한 후 month는 11 대신 10의 값을 얻습니다. 왜 그런가요?


월은 1이 아닌 0에서 인덱싱되므로 10은 11 월이고 11은 12 월입니다.


0부터 시작합니다- 문서 확인


많은 답변에서 분명히 알 수 있듯이 월은 0으로 시작합니다.

여기에 팁이 있습니다. SimpleDateFormat을 사용하여 해당 월의 문자열 표현을 가져와야합니다.

Calendar rightNow = Calendar.getInstance();
java.text.SimpleDateFormat df1 = new java.text.SimpleDateFormat("MM");
java.text.SimpleDateFormat df2 = new java.text.SimpleDateFormat("MMM");
java.text.SimpleDateFormat df3 = new java.text.SimpleDateFormat("MMMM");
System.out.println(df1.format(rightNow.getTime()));
System.out.println(df2.format(rightNow.getTime()));
System.out.println(df3.format(rightNow.getTime()));

산출:

11
Nov
November

참고 : 출력은 다를 수 있으며 로케일에 따라 다릅니다.


여러 사람이 지적했듯이 Java CalendarDate 클래스에서 반환 된 월은 1이 아닌 0에서 인덱싱됩니다. 따라서 0은 1 월이고 현재 월인 11 월은 10입니다.

왜 이것이 사실인지 궁금 할 것입니다. 기원은 POSIX 표준 기능과 거짓말 ctime, gmtime그리고 localtime그대로 사용하거나 반환, time_t(에서 다음 필드 구조를 사람이 3 ctime이 ) :

int tm_mday;    /* day of month (1 - 31) */
int tm_mon;     /* month of year (0 - 11) */
int tm_year;    /* year - 1900 */

이 API는 Java 1.0의 Java Date 클래스에 거의 정확하게 복사되었으며 대부분 Java 1.1의 Calendar 클래스에 그대로 복사되었습니다. Sun은 Calendar를 도입했을 때 가장 눈에 띄는 문제를 해결했습니다. 즉, 그레고리력의 2001 년이 Date 클래스의 값 101로 표시된다는 사실입니다. 그러나 왜 그들이 일과 월 값을 0 또는 1에서 색인화에서 일관되게 변경하지 않은지 잘 모르겠습니다. 이러한 불일치 및 관련 혼란은 오늘날까지도 Java (및 C)에 존재합니다.


목록의 색인처럼 월은 0부터 시작합니다.

따라서 Jan = 0, Feb = 1 등입니다.


API에서 :

한 해의 첫 번째 달은 1 월 (0)입니다. 마지막은 1 년의 개월 수에 따라 다릅니다.

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html


tl; dr

LocalDate.now()            // Returns a date-only `LocalDate` object for the current month of the JVM’s current default time zone.
         .getMonthValue()  // Returns 1-12 for January-December.

세부

다른 답변은 정확하지만 구식입니다.

귀찮은 오래된 날짜-시간 수업에는 잘못된 디자인 선택과 결함이 많았습니다. 하나는 명백한 1-12가 아니라 0-11의 월 수를 0으로 계산하는 것입니다.

java.time

java.time의 프레임 워크는 나중에 자바 8에 내장되어 있습니다. 이 클래스는 다음과 같은 기존의 번잡 한 날짜 - 시간의 수업을 대신하는 java.util.Date, .Calendar, java.text.SimpleDateFormat.

이제 유지 관리 모드 에서 Joda-Time 프로젝트는 java.time으로의 마이그레이션도 권장합니다.

자세한 내용은 Oracle Tutorial을 참조하십시오 . 그리고 많은 예제와 설명을 위해 Stack Overflow를 검색하십시오.

많은 java.time 기능은 자바 6 7 백 포팅 ThreeTen - 백 포트 및 상기 안드로이드 적응 ThreeTenABP .

ThreeTen - 추가 프로젝트 추가 클래스와 java.time를 확장합니다. 이 프로젝트는 java.time에 향후 추가 될 수있는 가능성을 입증하는 곳입니다.

1-12 개월

java.time에서 월 숫자는 실제로 1 월 -12 월에 예상되는 1-12입니다.

LocalDate클래스는 시간이 하루의 시간 영역없이없이 날짜 만 값을 나타냅니다.

시간대

시간대는 날짜를 결정하는 데 중요합니다. 주어진 순간에 날짜는 지역별로 전 세계적으로 다릅니다. 예를 들어, 파리 에서 자정 이후 몇 분이 지나면 프랑스몬트리올 퀘벡 에서는 여전히 '어제'인 새로운 날 입니다.

지정 적절한 시간대 이름 의 형식 continent/region예컨대, America/Montreal, Africa/Casablanca, 또는 Pacific/Auckland. EST또는 IST같은 3-4 자 약어 표준 시간대 아니고 , 표준화되지 않았으며, 고유하지도 않은 (!)이므로 사용하지 마십시오.

LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
int month = today.getMonthValue();  // Returns 1-12 as values.

시간대의 날짜-시간을 원하는 경우 ZonedDateTime동일한 방식으로 object를 사용 하십시오.

ZonedDateTime now = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) );
int month = now.getMonthValue();  // Returns 1-12 as values.

레거시 클래스 변환

If you have a GregorianCalendar object in hand, convert to ZonedDateTime using new toZonedDateTime method added to the old class. For more conversion info, see Convert java.util.Date to what “java.time” type?

ZonedDateTime zdt = myGregorianCalendar.toZonedDateTime();
int month = zdt.getMonthValue();  // Returns 1-12 as values.

Month enum

The java.time classes include the handy Month enum, by the way. Use instances of this class in your code rather than mere integers to make your code more self-documenting, provide type-safety, and ensure valid values.

Month month = today.getMonth();  // Returns an instant of `Month` rather than integer.

The Month enum offers useful methods such as generating a String with the localized name of the month.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


cal.get(Calendar.MONTH) + 1;

The above statement gives the exact number of the month. As get(Calendar.Month) returns month starting from 0, adding 1 to the result would give the correct output. And keep in mind to subtract 1 when setting the month.

cal.set(Calendar.MONTH, (8 - 1));

Or use the constant variables provided.

cal.set(Calendar.MONTH, Calendar.AUGUST);

It would be better to use

Calendar.JANUARY

which is zero ...

참고URL : https://stackoverflow.com/questions/1755199/calendar-returns-wrong-month

반응형