Android format calendar for time output

I use the code below to set an alarm. I would like to indicate what time it would be for this. I do not know if I will be mistaken. If I output the variable cal, it has a long string of information. How to extract only an hour and minutes?

    Calendar cal = Calendar.getInstance();
    // add 5 minutes to the calendar object
    cal.add(Calendar.MINUTE, 464);
+5
source share
2 answers

Use the get () method for your object Calendarand use static constants Calendarfor the desired field (hour, minute, etc.).

For instance:

cal.get(Calendar.Minute);
+6
source

You can use static constants, as m0skit0 says, or use SimpleDateFormat. Here is some code to display both methods:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 464);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
System.out.println(sdf.format(cal.getTime()));
System.out.println(cal.get(Calendar.HOUR)+":"+cal.get(Calendar.MINUTE));

outputs:

05:31
5:31
+23
source

All Articles