Reputation: 24223
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.
Upvotes: 1
Views: 1071
Reputation: 1
For those who are still having some problems with this, like I did, especially when you want to print multiple times you may need to to use new like follows:
System.out.println(""+new GregorianCalendar().get(Calendar.HOUR_OF_DAY)+":"+new GregorianCalendar().get(Calendar.MINUTE)+":"+new GregorianCalendar().get(Calendar.SECOND)+":"+new GregorianCalendar().get(Calendar.MILLISECOND));
Upvotes: 0
Reputation: 298
Calendar.HOUR
(or MINUTE
, SECOND
) is just an indicator that indicates which field we want to extract from the Calendar
instance, not the value, i.e. we want to 'extract HOUR from the calendar object' like below:
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY); // in 24-hours,
// or c.get(Calendar.HOUR) in 12-hours.
int minute = c.get(Calendar.MINUTE);
int second = c.get(Calendar.SECOND);
int weekday = c.get(Calendar.DAY_OF_WEEK);
int weekOfYear = c.get(Calendar.WEEK_OF_YEAR);
Upvotes: 0
Reputation: 359
I am not sure what is requirement but if you want system time then may be you can use this "System.currentTimeMillis()"
Upvotes: 0
Reputation: 5291
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()
.
Upvotes: 3
Reputation: 3608
Calendar.HOUR
, Calendar.MINUTE
and Calendar.SECOND
are public static int
field of the Calendar
class. Their value is
Your String
concatenation is just appending this values. To read from a Calendar
you could so something similar to
calendar.get(Calendar.HOUR);
calendar.get(Calendar.MINUTE);
Upvotes: 3