問題描述
所以我現在在這里待了幾個小時,它返回了正確的年份和日期,但由于某些奇怪的原因,它返回了錯誤的月份.我確定這是一個簡單的解決方法,但我似乎無法弄清楚.
package gregoriancalendar;導入 java.util.GregorianCalendar;公共課 Calendar8_5 {公共靜態無效主要(字符串[]參數){GregorianCalendar 日歷 = new GregorianCalendar();System.out.println("當前年月日:");System.out.println("年份是" + calendar.get(1));System.out.println("月份是" + calendar.get(2));System.out.println("今天是" + calendar.get(5));calendar.setTimeInMillis(1234567898765L);//經過時間System.out.println("設置值為1234567898765L");System.out.println("年份是" + calendar.get(1));System.out.println("月份是" + calendar.get(2));System.out.println("今天是" + calendar.get(5));}}
tl;dr
要獲取當前月份的數字 1-12:
LocalDate.now().getMonthValue()
最好指定您想要/預期的時區.
LocalDate.now(ZoneId.of("美國/蒙特利爾")).getMonthValue()
類似調用.getYear()
和.getDayOfMonth()
.
詳情
<塊引用>返回錯誤的月份
正如其他人所說,在 Calendar
中,1 月至 12 月的月份瘋狂地編號為 0-11,而不是 1-12.舊日期時間類中許多糟糕的設計決策之一.這些類現在是遺留的,被 java.time 類所取代.
那么有辦法解決這個問題嗎?
是的,有一個解決方法.使用一個好的日期時間庫而不是 java.util.Date/Calendar 的混亂.現代方式是使用 java.time 類.
當前時刻
時區對于獲取當前日期和時間至關重要.對于任何給定的時刻,日期和掛鐘時間因地區而異.
ZoneId z = ZoneId.of("美國/蒙特利爾");ZonedDateTime zdt = ZonedDateTime.now(z);
您可以通過 Month
枚舉和日期.
System.out.println("當前:" + zdt);System.out.println("年份是" + zdt.getYear());System.out.println("月份是" + zdt.getMonthValue());System.out.println( "月份名稱為 " + zdt.getMonth().getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) );//或 Locale.US、Locale.ITALY 等.System.out.println("天是" + zdt.getDayOfMonth());
<塊引用>
當前:2016-12-14T04:54:44.802-05:00[美國/蒙特利爾]
2016 年
月份是 12
月份名稱是十二月
第 14 天
查看 IdeOne.com 中的實時代碼.
如果您只關心日期而不關心時間,請使用 LocalDate
類.
LocalDate.now(z);
特定時刻
您可以將時刻指定為自 epoch 以來的毫秒數1970 年 UTC 的第一刻.
長輸入 = 1_234_567_898_765L ;Instant Instant = Instant.ofEpochMilli( 輸入 );
<塊引用>
instant.toString(): 2009-02-13T23:31:38.765Z
該輸出中的 Z
是 Zulu
的縮寫,意思是 UTC.
您可以指定時區以調整到特定的掛鐘時間.
ZoneId z = ZoneId.of("美國/蒙特利爾");ZonedDateTime zdt = instant.atZone(z);
<塊引用>
zdt.toString(): 2009-02-13T18:31:38.765-05:00[美國/蒙特利爾]
查看IdeOne.com 中的實時代碼.
我確實不建議以這種方式交換日期時間數據.最好序列化為 ISO 8601 格式的文本.例如:2009-02-13T23:31:38.765Z
關于java.time
java.time 框架內置于 Java 8 及更高版本.這些類取代了麻煩的舊 legacy 日期時間類,例如 java.util.Date
, 日歷
, &SimpleDateFormat
.
Joda-Time 項目,現在在 維護模式,建議遷移到 java.time 類.
要了解更多信息,請參閱 Oracle 教程.并在 Stack Overflow 上搜索許多示例和解釋.規范是 JSR 310.
從哪里獲得 java.time 類?
- Java SE 8 和 SE 9 及更高版本
- 內置.
- 標準 Java API 的一部分,帶有捆綁實現.
- Java 9 添加了一些小功能和修復.
- Java SE 6 和 SE 7
- 大部分 java.time 功能都向后移植到 Java 6 &7 在 ThreeTen-Backport.
- Android
- ThreeTenABP 項目采用 ThreeTen-專門針對 Android 的反向移植(如上所述).
- 請參閱如何使用…….
ThreeTen-Extra 項目通過附加類擴展了 java.time.該項目是未來可能添加到 java.time 的試驗場.您可以在這里找到一些有用的類,例如 間隔
,YearWeek
, YearQuarter
和 更多.
舊答案 - Joda-Time
更新:Joda-Time 項目,現在在 維護模式,建議遷移到 java.time 類.
- 現在使用 Joda-Time 2.3.
- 未來,在 Java 8 中,考慮遷移到 JSR 310:日期和時間API 取代了 Date/Calendar 類,并受到 Joda-Time 的啟發.
示例代碼
今天
//? 2013 Basil Bourque.任何為此承擔全部責任的人都可以永遠免費使用此源代碼.//導入 o??rg.joda.time.*;//通常最好明確時區而不是依賴默認值.DateTimeZone denverTimeZone = DateTimeZone.forID("美國/丹佛");java.util.Locale locale = Locale.FRANCE;現在日期時間 = 新日期時間(denverTimeZone);System.out.println("當前年月日:" + now );System.out.println("年份是" + now.year().getAsText(locale));System.out.println("月份是" + now.monthOfYear().getAsText(locale));System.out.println("今天是" + now.dayOfMonth().getAsText(locale));System.out.println();//空行.
運行時……
當前年月&日期:2013-12-04T01:58:24.322-07:00年份是 2013 年月份是十二月天是 4
有一天
//專注于整數來處理日期時間通常不是一個好主意,但你要求它.日期時間 someDateTime = new DateTime(1234567898765L, DateTimeZone.UTC);System.out.println("1234567898765L的設置值為:" + someDateTime );System.out.println("年份是" + someDateTime.year().getAsText(locale));System.out.println("月份是" + someDateTime.monthOfYear().getAsText(locale));System.out.println("月份是" + someDateTime.dayOfMonth().getAsText(locale));System.out.println("星期幾是" + someDateTime.dayOfWeek().getAsText(locale));System.out.println("一年中的哪一天是" + someDateTime.dayOfYear().getAsText(locale));
運行時……
1234567898765L的設置值為:2009-02-13T23:31:38.765Z年份是 2009月份是 février一個月中的第 13 天星期幾是 vendredi一年中的第 44 天
<小時>
附:當我注意到你隨意選擇的龍導致了十三號星期五時,我的背脊發涼!
So I been at this for a few hours now and it returns the correct Year, and Day but for some odd reason it returns the wrong month. I'm sure its a simple fix but I can't seem to figure it out.
package gregoriancalendar;
import java.util.GregorianCalendar;
public class Calendar8_5 {
public static void main(String[] args){
GregorianCalendar calendar = new GregorianCalendar();
System.out.println("Current Year, Month & Date: ");
System.out.println("Year is " + calendar.get(1));
System.out.println("Month is " + calendar.get(2));
System.out.println("Day is " + calendar.get(5));
calendar.setTimeInMillis(1234567898765L);
//Elapse Time
System.out.println("Set Value of 1234567898765L");
System.out.println("Year is " + calendar.get(1));
System.out.println("Month is " + calendar.get(2));
System.out.println("Day is " + calendar.get(5));
}
}
tl;dr
To get a number 1-12 for current month:
LocalDate.now()
.getMonthValue()
Better to specify your desired/expected time zone.
LocalDate.now(
ZoneId.of( "America/Montreal" )
).getMonthValue()
Similarly call .getYear()
and .getDayOfMonth()
.
Details
it returns the wrong month
As others said, in Calendar
the months January-December are crazily numbered 0-11 rather than 1-12. One of many poor design decisions in the old date-time classes. Those classes are now legacy, supplanted by the java.time classes.
So is there a work around this?
Yes, there is a workaround. Use a good date-time library rather than the mess that is java.util.Date/Calendar. The modern way is with the java.time classes.
Current moment
Time zone is crucial in getting the current date and time. For any given moment the date and wall-clock time vary by zone.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( z );
You can interrogate for the various components such as year, month number, localized name of month via Month
enum, and day-of-month.
System.out.println ( "Current: " + zdt );
System.out.println( "Year is " + zdt.getYear() );
System.out.println( "Month is " + zdt.getMonthValue() );
System.out.println( "Month name is " + zdt.getMonth().getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ); // Or Locale.US, Locale.ITALY, etc.
System.out.println( "Day is " + zdt.getDayOfMonth() );
Current: 2016-12-14T04:54:44.802-05:00[America/Montreal]
Year is 2016
Month is 12
Month name is décembre
Day is 14
See live code in IdeOne.com.
If you only care about the date and not the time-of-day, use the LocalDate
class.
LocalDate.now( z );
Specific moment
You can specify a moment as a count of milliseconds since the epoch of first moment of 1970 in UTC.
long input = 1_234_567_898_765L ;
Instant instant = Instant.ofEpochMilli( input );
instant.toString(): 2009-02-13T23:31:38.765Z
The Z
in that output is short for Zulu
and means UTC.
You can assign a time zone to adjust into a particular wall-clock time.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
zdt.toString(): 2009-02-13T18:31:38.765-05:00[America/Montreal]
See live code in IdeOne.com.
I do not recommend exchanging date-time data this way. Better to serialize to text in ISO 8601 formats. For example: 2009-02-13T23:31:38.765Z
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?
- Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
- See How to use….
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.
Old Answer - Joda-Time
Update: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
- Use Joda-Time 2.3 now.
- In the future, with Java 8, consider moving to JSR 310: Date and Time API which supplants the Date/Calendar classes and is inspired by Joda-Time.
Example Code
Today
// ? 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// Generally best to be explicit about time zone rather than depend on default.
DateTimeZone denverTimeZone = DateTimeZone.forID( "America/Denver" );
java.util.Locale locale = Locale.FRANCE;
DateTime now = new DateTime( denverTimeZone );
System.out.println( "Current Year, Month & Day for: " + now );
System.out.println( "Year is " + now.year().getAsText( locale ) );
System.out.println( "Month is " + now.monthOfYear().getAsText( locale ) );
System.out.println( "Day is " + now.dayOfMonth().getAsText( locale ) );
System.out.println(); // blank line.
When run…
Current Year, Month & Day for: 2013-12-04T01:58:24.322-07:00
Year is 2013
Month is décembre
Day is 4
Some Day
// Not generally a good idea to focus on integers for working with date-time, but you asked for it.
DateTime someDateTime = new DateTime( 1234567898765L, DateTimeZone.UTC );
System.out.println( "Set Value of 1234567898765L is: " + someDateTime );
System.out.println( "Year is " + someDateTime.year().getAsText( locale ) );
System.out.println( "Month is " + someDateTime.monthOfYear().getAsText( locale ) );
System.out.println( "Day of month is " + someDateTime.dayOfMonth().getAsText( locale ) );
System.out.println( "Day of week is " + someDateTime.dayOfWeek().getAsText( locale ) );
System.out.println( "Day of year is " + someDateTime.dayOfYear().getAsText( locale ) );
When run…
Set Value of 1234567898765L is: 2009-02-13T23:31:38.765Z
Year is 2009
Month is février
Day of month is 13
Day of week is vendredi
Day of year is 44
P.S. I just got the chills down my back when I noticed your arbitrarily chosen Long resulted in Friday The Thirteenth!
這篇關于Java 公歷返回錯誤的月份的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!