Below is my code.
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 is supposed to give me
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.
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?
Thanks.
解决方案
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);
}
}
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().