0

I'm trying to write a method to return a Time in util.Date to a string. I am getting '0' when i am trying to return whether the time is in AM or PM and the minutes are not displaying the 0 in front. I am trying to return the time in the format of HH:mm am_pm

Here is my method:

public String getTime() {
  Calendar cal = Calendar.getInstance();
  int hr = cal.get(Calendar.HOUR);
  int min = cal.get(Calendar.MINUTE);

  return String.valueOf(hr) + ":" + String.valueOf(min) + " " + cal.get(Calendar.AM_PM);
}

Input: 2:00 (HH:mm SimpleDateFormat in a JFormattedTextField)

Output: 2:0 0

EDIT: tried using the SimpleDateFormat but i am getting a type mistmatch error

public String getTime()
{
    SimpleDateFormat format = new SimpleDateFormat("HH:mm aa");
    date = format.toString().toString();
    return date;
}
user1352609
  • 145
  • 2
  • 12

3 Answers3

3

Something like this will do:

DateFormat df = new SimpleDateFormat("hh:mm aa");
String timeNow = df.format(new Date());
gerrytan
  • 40,313
  • 9
  • 84
  • 99
0

Use SimpleDateFormat instead.

public String getTime() {
    // If you want the current hour
    SimpleDateFormat format = new SimpleDateFormat("HH:mm aa");
    return format.format(new Date());
}
Diogo Moreira
  • 1,082
  • 2
  • 9
  • 24
0

cal.get(Calendar.AM_PM) returns 0 for AM and 1 for PM. Replace the last line with:

return String.valueOf(hr) + ":" + String.valueOf(min) + " " + cal.get(Calendar.AM_PM) == Calendar.AM ? "am" : "pm";

Consider using SimpleDateFormat.

Svilen Ivanov
  • 359
  • 1
  • 12