pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

Java 公歷返回錯誤的月份

Java Gregorian Calendar Returns Wrong Month(Java 公歷返回錯誤的月份)
本文介紹了Java 公歷返回錯誤的月份的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

限時送ChatGPT賬號..

所以我現在在這里待了幾個小時,它返回了正確的年份和日期,但由于某些奇怪的原因,它返回了錯誤的月份.我確定這是一個簡單的解決方法,但我似乎無法弄清楚.

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

該輸出中的 ZZulu 的縮寫,意思是 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 8SE 9 及更高版本
    • 內置.
    • 標準 Java API 的一部分,帶有捆綁實現.
    • Java 9 添加了一些小功能和修復.
  • Java SE 6SE 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模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

Parsing an ISO 8601 string local date-time as if in UTC(解析 ISO 8601 字符串本地日期時間,就像在 UTC 中一樣)
How to convert Gregorian string to Gregorian Calendar?(如何將公歷字符串轉換為公歷?)
Java: What/where are the maximum and minimum values of a GregorianCalendar?(Java:GregorianCalendar 的最大值和最小值是什么/在哪里?)
Calendar to Date conversion for dates before 15 Oct 1582. Gregorian to Julian calendar switch(1582 年 10 月 15 日之前日期的日歷到日期轉換.公歷到儒略歷切換)
java Calendar setFirstDayOfWeek not working(java日歷setFirstDayOfWeek不起作用)
Java: getting current Day of the Week value(Java:獲取當前星期幾的值)
主站蜘蛛池模板: 银川美容培训-美睫美甲培训-彩妆纹绣培训-新娘化妆-学化妆-宁夏倍莱妮职业技能培训学校有限公司 临时厕所租赁_玻璃钢厕所租赁_蹲式|坐式厕所出租-北京慧海通 | MVE振动电机_MVE震动电机_MVE卧式振打电机-河南新乡德诚生产厂家 | 武汉画册印刷厂家-企业画册印刷-画册设计印刷制作-宣传画册印刷公司 - 武汉泽雅印刷厂 | 丙烷/液氧/液氮气化器,丙烷/液氧/液氮汽化器-无锡舍勒能源科技有限公司 | 合肥网带炉_安徽箱式炉_钟罩炉-合肥品炙装备科技有限公司 | 培训无忧网-教育培训咨询招生第三方平台 | 闪电优家-卫生间防水补漏_酒店漏水渗水维修_防水堵漏公司 | 撕碎机_轮胎破碎机_粉碎机_回收生产线厂家_东莞华达机械有限公司 | 魔方网-培训咨询服务平台| 二手Sciex液质联用仪-岛津气质联用仪-二手安捷伦气质联用仪-上海隐智科学仪器有限公司 | 分光色差仪,测色仪,反透射灯箱,爱色丽分光光度仪,美能达色差仪维修_苏州欣美和仪器有限公司 | 无硅导热垫片-碳纤维导热垫片-导热相变材料厂家-东莞市盛元新材料科技有限公司 | 江西自考网-江西自学考试网| 爱德华真空泵油/罗茨泵维修,爱发科-比其尔产品供应东莞/杭州/上海等全国各地 | 釜溪印象网络 - Powered by Discuz! | 立式壁挂广告机厂家-红外电容触摸一体机价格-华邦瀛 | 跨境物流_美国卡派_中大件运输_尾程派送_海外仓一件代发 - 广州环至美供应链平台 | 玉米加工设备,玉米深加工机械,玉米糁加工设备.玉米脱皮制糁机 华豫万通粮机 | 防爆暖风机_防爆电暖器_防爆电暖风机_防爆电热油汀_南阳市中通智能科技集团有限公司 | 伊卡洛斯软装首页-电动窗帘,别墅窗帘,定制窗帘,江浙沪1000+别墅窗帘案例 | 车充外壳,车载充电器外壳,车载点烟器外壳,点烟器连接头,旅行充充电器外壳,手机充电器外壳,深圳市华科达塑胶五金有限公司 | 政府回应:200块在义乌小巷能买到爱情吗?——揭秘打工族省钱约会的生存智慧 | 丙烷/液氧/液氮气化器,丙烷/液氧/液氮汽化器-无锡舍勒能源科技有限公司 | 大白菜官网,大白菜winpe,大白菜U盘装系统, u盘启动盘制作工具 | 真空乳化机-灌装封尾机-首页-温州精灌 | 防伪溯源|防窜货|微信二维码营销|兆信_行业内领先的防伪防窜货数字化营销解决方案供应商 | 电池高低温试验箱-气态冲击箱-双层电池防爆箱|简户百科 | 活性炭-蜂窝-椰壳-柱状-粉状活性炭-河南唐达净水材料有限公司 | 福州仿石漆加盟_福建仿石漆厂家-外墙仿石漆加盟推荐铁壁金钢(福建)新材料科技有限公司有保障 | 智慧旅游_智慧景区_微景通-智慧旅游景区解决方案提供商 | 电缆接头_防水接头_电缆防水接头 - 乐清市新豪电气有限公司 | 企业微信scrm管理系统_客户关系管理平台_私域流量运营工具_CRM、ERP、OA软件-腾辉网络 | 退火炉,燃气退火炉,燃气热处理炉生产厂家-丹阳市丰泰工业炉有限公司 | 世界箱包品牌十大排名,女包小众轻奢品牌推荐200元左右,男包十大奢侈品牌排行榜双肩,学生拉杆箱什么品牌好质量好 - Gouwu3.com | 驾驶式洗地机/扫地机_全自动洗地机_工业洗地机_荣事达工厂官网 | 高中学习网-高考生信息学习必备平台| 珠海白蚁防治_珠海灭鼠_珠海杀虫灭鼠_珠海灭蟑螂_珠海酒店消杀_珠海工厂杀虫灭鼠_立净虫控防治服务有限公司 | 华夏医界网_民营医疗产业信息平台_民营医院营销管理培训 | 碳纤维布-植筋胶-灌缝胶-固特嘉加固材料公司 | 武汉刮刮奖_刮刮卡印刷厂_为企业提供门票印刷_武汉合格证印刷_现金劵代金券印刷制作 - 武汉泽雅印刷有限公司 | 切铝机-数控切割机-型材切割机-铝型材切割机-【昆山邓氏精密机械有限公司】 |