Java Calendar always shows the same time

后端 未结 5 1840
天命终不由人
天命终不由人 2020-12-07 05:05

Below is my code.

public class TestCalendar {

public static void main(String[] args){
    int unique_id = Integer.parseInt(\"\" + Calendar.HOUR + Calendar.M         


        
相关标签:
5条回答
  • 2020-12-07 05:25

    Calendar.HOUR, Calendar.MINUTE and Calendar.SECOND are public static int field of the Calendar class. Their value is

    • CALENDAR.HOUR: 10
    • CALENDAR.MINUTE: 12 and
    • CALENDAR.SECOND: 13.

    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);
    
    0 讨论(0)
  • 2020-12-07 05:35

    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);
    
    0 讨论(0)
  • 2020-12-07 05:47

    I am not sure what is requirement but if you want system time then may be you can use this "System.currentTimeMillis()"

    0 讨论(0)
  • 2020-12-07 05:48

    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));
    
    0 讨论(0)
  • 2020-12-07 05:49

    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().

    0 讨论(0)
提交回复
热议问题