Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Format calendar to output time

Tags:

java

android

I am using the below code to set an alarm. I would like to output what the time for this would be. I don't know if I going about this the wrong way. If I output the variable cal it has a long string of information. How do I extract only the hour and minutes?

    Calendar cal = Calendar.getInstance();
    // add 5 minutes to the calendar object
    cal.add(Calendar.MINUTE, 464);
like image 900
Somk Avatar asked May 05 '12 15:05

Somk


People also ask

How do I change the date format on my Android calendar?

Date and Time in Android are formatted using the SimpleDateFormat library from Java, using Calendar instance which helps to get the current system date and time. The current date and time are of the type Long which can be converted to a human-readable date and time.

Which view is used to display the date and time in Android application?

text. DateFormat. getDateTimeInstance(). format(new Date()); // textView is the TextView view that should display it textView.


2 Answers

You can use the static constants as m0skit0 says, or use SimpleDateFormat. Here's some code to show 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
like image 113
dave.c Avatar answered Oct 19 '22 10:10

dave.c


Use the get() method on your Calendar object, and use Calendar static constants for the needed field (hour, minute, etc...).

For example:

cal.get(Calendar.Minute);
like image 33
m0skit0 Avatar answered Oct 19 '22 11:10

m0skit0