問(wèn)題描述
所以我現(xiàn)在在這里待了幾個(gè)小時(shí),它返回了正確的年份和日期,但由于某些奇怪的原因,它返回了錯(cuò)誤的月份.我確定這是一個(gè)簡(jiǎn)單的解決方法,但我似乎無(wú)法弄清楚.
package gregoriancalendar;導(dǎo)入 java.util.GregorianCalendar;公共課 Calendar8_5 {公共靜態(tài)無(wú)效主要(字符串[]參數(shù)){GregorianCalendar 日歷 = new GregorianCalendar();System.out.println("當(dāng)前年月日:");System.out.println("年份是" + calendar.get(1));System.out.println("月份是" + calendar.get(2));System.out.println("今天是" + calendar.get(5));calendar.setTimeInMillis(1234567898765L);//經(jīng)過(guò)時(shí)間System.out.println("設(shè)置值為1234567898765L");System.out.println("年份是" + calendar.get(1));System.out.println("月份是" + calendar.get(2));System.out.println("今天是" + calendar.get(5));}}
tl;dr
要獲取當(dāng)前月份的數(shù)字 1-12:
LocalDate.now().getMonthValue()
最好指定您想要/預(yù)期的時(shí)區(qū).
LocalDate.now(ZoneId.of("美國(guó)/蒙特利爾")).getMonthValue()
類似調(diào)用.getYear()
和.getDayOfMonth()
.
詳情
<塊引用>返回錯(cuò)誤的月份
正如其他人所說(shuō),在 Calendar
中,1 月至 12 月的月份瘋狂地編號(hào)為 0-11,而不是 1-12.舊日期時(shí)間類中許多糟糕的設(shè)計(jì)決策之一.這些類現(xiàn)在是遺留的,被 java.time 類所取代.
那么有辦法解決這個(gè)問(wèn)題嗎?
是的,有一個(gè)解決方法.使用一個(gè)好的日期時(shí)間庫(kù)而不是 java.util.Date/Calendar 的混亂.現(xiàn)代方式是使用 java.time 類.
當(dāng)前時(shí)刻
時(shí)區(qū)對(duì)于獲取當(dāng)前日期和時(shí)間至關(guān)重要.對(duì)于任何給定的時(shí)刻,日期和掛鐘時(shí)間因地區(qū)而異.
ZoneId z = ZoneId.of("美國(guó)/蒙特利爾");ZonedDateTime zdt = ZonedDateTime.now(z);
您可以通過(guò) Month
枚舉和日期.
System.out.println("當(dāng)前:" + 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());
<塊引用>
當(dāng)前:2016-12-14T04:54:44.802-05:00[美國(guó)/蒙特利爾]
2016 年
月份是 12
月份名稱是十二月
第 14 天
查看 IdeOne.com 中的實(shí)時(shí)代碼.
如果您只關(guān)心日期而不關(guān)心時(shí)間,請(qǐng)使用 LocalDate
類.
LocalDate.now(z);
特定時(shí)刻
您可以將時(shí)刻指定為自 epoch 以來(lái)的毫秒數(shù)1970 年 UTC 的第一刻.
長(zhǎng)輸入 = 1_234_567_898_765L ;Instant Instant = Instant.ofEpochMilli( 輸入 );
<塊引用>
instant.toString(): 2009-02-13T23:31:38.765Z
該輸出中的 Z
是 Zulu
的縮寫,意思是 UTC.
您可以指定時(shí)區(qū)以調(diào)整到特定的掛鐘時(shí)間.
ZoneId z = ZoneId.of("美國(guó)/蒙特利爾");ZonedDateTime zdt = instant.atZone(z);
<塊引用>
zdt.toString(): 2009-02-13T18:31:38.765-05:00[美國(guó)/蒙特利爾]
查看IdeOne.com 中的實(shí)時(shí)代碼.
我確實(shí)不建議以這種方式交換日期時(shí)間數(shù)據(jù).最好序列化為 ISO 8601 格式的文本.例如:2009-02-13T23:31:38.765Z
關(guān)于java.time
java.time 框架內(nèi)置于 Java 8 及更高版本.這些類取代了麻煩的舊 legacy 日期時(shí)間類,例如 java.util.Date
, 日歷
, &SimpleDateFormat
.
Joda-Time 項(xiàng)目,現(xiàn)在在 維護(hù)模式,建議遷移到 java.time 類.
要了解更多信息,請(qǐng)參閱 Oracle 教程.并在 Stack Overflow 上搜索許多示例和解釋.規(guī)范是 JSR 310.
從哪里獲得 java.time 類?
- Java SE 8 和 SE 9 及更高版本
- 內(nèi)置.
- 標(biāo)準(zhǔn) Java API 的一部分,帶有捆綁實(shí)現(xiàn).
- Java 9 添加了一些小功能和修復(fù).
- Java SE 6 和 SE 7
- 大部分 java.time 功能都向后移植到 Java 6 &7 在 ThreeTen-Backport.
- Android
- ThreeTenABP 項(xiàng)目采用 ThreeTen-專門針對(duì) Android 的反向移植(如上所述).
- 請(qǐng)參閱如何使用…….
ThreeTen-Extra 項(xiàng)目通過(guò)附加類擴(kuò)展了 java.time.該項(xiàng)目是未來(lái)可能添加到 java.time 的試驗(yàn)場(chǎng).您可以在這里找到一些有用的類,例如 間隔
,YearWeek
, YearQuarter
和 更多.
舊答案 - Joda-Time
更新:Joda-Time 項(xiàng)目,現(xiàn)在在 維護(hù)模式,建議遷移到 java.time 類.
- 現(xiàn)在使用 Joda-Time 2.3.
- 未來(lái),在 Java 8 中,考慮遷移到 JSR 310:日期和時(shí)間API 取代了 Date/Calendar 類,并受到 Joda-Time 的啟發(fā).
示例代碼
今天
//? 2013 Basil Bourque.任何為此承擔(dān)全部責(zé)任的人都可以永遠(yuǎn)免費(fèi)使用此源代碼.//導(dǎo)入 o??rg.joda.time.*;//通常最好明確時(shí)區(qū)而不是依賴默認(rèn)值.DateTimeZone denverTimeZone = DateTimeZone.forID("美國(guó)/丹佛");java.util.Locale locale = Locale.FRANCE;現(xiàn)在日期時(shí)間 = 新日期時(shí)間(denverTimeZone);System.out.println("當(dāng)前年月日:" + 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();//空行.
運(yùn)行時(shí)……
當(dāng)前年月&日期:2013-12-04T01:58:24.322-07:00年份是 2013 年月份是十二月天是 4
有一天
//專注于整數(shù)來(lái)處理日期時(shí)間通常不是一個(gè)好主意,但你要求它.日期時(shí)間 someDateTime = new DateTime(1234567898765L, DateTimeZone.UTC);System.out.println("1234567898765L的設(shè)置值為:" + 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));
運(yùn)行時(shí)……
1234567898765L的設(shè)置值為:2009-02-13T23:31:38.765Z年份是 2009月份是 février一個(gè)月中的第 13 天星期幾是 vendredi一年中的第 44 天
<小時(shí)>
附:當(dāng)我注意到你隨意選擇的龍導(dǎo)致了十三號(hào)星期五時(shí),我的背脊發(fā)涼!
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!
這篇關(guān)于Java 公歷返回錯(cuò)誤的月份的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!