Java Calendar Setting Incorrectly

不打扰是莪最后的温柔 提交于 2019-12-02 14:01:20

问题


I'm having some trouble with Java's Calendar. I'm parsing some data from a txt file, and need to create a date. After completion of the following code:

tmpYear = Double.parseDouble(row[yearIndex]);
tmpMonth = Double.parseDouble(row[monthIndex]);
tmpDay = Double.parseDouble(row[dayIndex]);
if(timeIndex != -1)
    tmpTime = Double.parseDouble(row[timeIndex]);
if(secondsIndex != -1)
    tmpSeconds = Double.parseDouble(row[secondsIndex]);

I can debug and see that the variables are as follows: tmpYear == 2010
tmpMonth == 12
tmpDay == 30
tmpTime == 15 (This is the hour of the day)
tmpSeconds == 0

But when running the following code:

cal.set((int)tmpYear,(int)tmpMonth,(int)tmpDay,(int)tmpTime,
            (int)((tmpTime - (int)tmpTime)*100),(int)tmpSeconds);
System.out.println(cal.getTime().toString());

I'm getting this for an output:
Sun Jan 30 15:00:00 CST 2011

Can someone explain what a possible reason for this would be? Thank you all in advance for the help!


回答1:


months are indexed 0-11 instead of 1-12.
0 = January
1 = February
...
11 = December
Use tmpMonth = value -1 instead.




回答2:


I believe the month's value starts at 0 rather than 1 so it interprets 0 as Jan, 1 as Feb ... and then Jan again as 12.




回答3:


From the API:

month - the value used to set the MONTH time field. Month value is 0-based. e.g., 0 for January.




回答4:


When you set the Calendar.MONTH field, it is zero-based. {January=0... December=11}




回答5:


The reason is quite simple: design fault in the Calendar API. That's why the JSR 310 is on its way in order to improve the java support for dates.

Technically, the authors of the class thought it was good to use only static fields. So what you need to do is to use the following:

calendar = ...
calendar.setMonth(Calendar.JANUARY);

They didn't think that people might need dynamic settings to a calendar, just like you need (and most of us, for that matters).




回答6:


The month values go from 0 (January) to 11 (December). Try using ((int) tmpMonth) - 1 when setting the month to get December.



来源:https://stackoverflow.com/questions/4598036/java-calendar-setting-incorrectly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!