問題描述
下面是我的代碼.
public class TestCalendar {
public static void main(String[] args){
int unique_id = Integer.parseInt("" + Calendar.HOUR + Calendar.MINUTE
+ Calendar.SECOND);
System.out.println(unique_id);
}
}
Calendar.HOUR 應(yīng)該給我
Calendar.HOUR is supposed to give me
public static final int HOUR 用于獲取和設(shè)置的字段編號,指示早上的時間或下午.HOUR 用于 12 小時制 (0 - 11).中午和午夜用 0 表示,而不是到 12 點(diǎn).例如,在晚上 10:04:15.250,HOUR 是 10.
public static final int HOUR Field number for get and set indicating the hour of the morning or afternoon. HOUR is used for the 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12. E.g., at 10:04:15.250 PM the HOUR is 10.
無論我運(yùn)行多少次代碼,它總是給我相同的 unique_id.(101213),我機(jī)器上的當(dāng)?shù)貢r間是下午 1:30.我在這里做錯了什么?
It doesnt matter how many times I run this code, it always gives me the same unique_id. (101213) and my local time on my machine is 1:30pm. What am I doing wrong here?
謝謝.
推薦答案
您的代碼只是連接常量,Calendar 定義這些常量以識別其中的一些字段.要獲取這些字段的值,請調(diào)用 Calendar.get()
并將常量標(biāo)識符作為參數(shù)傳遞:
Your code is just concatenating constants, that the Calendar defines to identify some of it's fields. To get values of these fields, call Calendar.get()
and pass the constant identifier as an argument:
public class TestCalendar {
public static void main(String[] args){
Calendar c = Calendar.getInstance();
int unique_id = Integer.parseInt("" + c.get(Calendar.HOUR) + c.get(Calendar.MINUTE)
+ c.get(Calendar.SECOND));
System.out.println(unique_id);
}
}
上述方法可行,但結(jié)果與唯一 ID 相差甚遠(yuǎn).要獲得唯一標(biāo)識時間點(diǎn)的 ID(精度為毫秒),請考慮 Calendar.getTimeInMillis()
.
The above would work, but the result will be far from unique ID.
To get an ID uniquely identifying a point in time (with the precision of milliseconds), consider Calendar.getTimeInMillis()
.
這篇關(guān)于Java 日歷總是顯示相同的時間的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!