在這兩種情況下,我想在這個例子中米利斯要設置的日期爲1395227280627
,並且在人類可讀的格式是3/19/2014 12:08:00 PM
爲什麼其中一種方法適用於設定日期,另一種方法不適用?
1)這是第一種方法,它不能正常工作:
Calendar ret1=GregorianCalendar.getInstance();
ret1.set(Calendar.YEAR, year);
ret1.set(Calendar.MONTH, month);
ret1.set(Calendar.DAY_OF_YEAR, day);
ret1.set(Calendar.HOUR_OF_DAY, hour);
ret1.set(Calendar.MINUTE, minute);
ret1.set(Calendar.SECOND, 0);
Log.e("Time in millis:", Long.toString(ret1.getTimeInMillis()));
這種方法的輸出是毫秒爲1390129680626
,而人類可讀格式爲1/19/2014 12:08:00 PM
。問題是,這個月沒有正確設置。
2)第二種方法,其正確的工作原理是:
Calendar ret2=GregorianCalendar.getInstance();
ret2.set(year, month, day, hour, minute, 0);
Log.e("Time in millis:", Long.toString(ret2.getTimeInMillis()));
這種方法的輸出是1395227280627
以毫秒計,並且在人類可讀的格式3/19/2014 12:08:00 PM
,所以我想要什麼。我很好奇哪裏出了問題,經過一番研究,大量的人工智能表明Java日曆非常糟糕,並且有很多非常奇怪的事情,包括一些破碎的部分。我已經開始走回頭路,其工作方式方法,下面是結果:
回溯calendar.set(year, month, day, hour, minute, second)
/**
* Sets the year, month, day of the month, hour of day, minute, and second fields.
* Other fields are not changed; call {@link #clear} first if this is not desired.
* The month value is 0-based, so it may be clearer to use a constant like {@code JANUARY}.
*/
public final void set(int year, int month, int day, int hourOfDay, int minute, int second) {
set(year, month, day, hourOfDay, minute);
set(SECOND, second);
}
所以second
部分轉化爲正是我在第一種方法一樣,檢查。
回溯calendar.set(year, month, day, hourOfDay, minute)
/**
* Sets the year, month, day of the month, hour of day, and minute fields.
* Other fields are not changed; call {@link #clear} first if this is not desired.
* The month value is 0-based, so it may be clearer to use a constant like {@code JANUARY}.
*/
public final void set(int year, int month, int day, int hourOfDay, int minute) {
set(year, month, day);
set(HOUR_OF_DAY, hourOfDay);
set(MINUTE, minute);
}
所以hourOfDay
和minute
部分轉化爲正是我在第一種方法一樣,檢查。
回溯calendar.set(year, month, day)
/**
* Sets the year, month, and day of the month fields.
* Other fields are not changed; call {@link #clear} first if this is not desired.
* The month value is 0-based, so it may be clearer to use a constant like {@code JANUARY}.
*/
public final void set(int year, int month, int day) {
set(YEAR, year);
set(MONTH, month);
set(DATE, day);
}
所以year
,month
和day
部分恰好轉化爲我在第一種方法一樣。
結論是,我在第一種方法中所做的每個調用都以完全相同的方式在第二種方法中調用,所以我不明白,發生了什麼。任何人都可以幫助我解決這個問題,並解釋爲什麼會發生這種情況?
哦,上帝,我多麼愚蠢是...這完全溜過去,謝謝。 – hundeva