spentak
spentak

Reputation: 4727

Java Date - Android Time Picker

I'm having trouble getting the right format here. I'm trying to get a proper date from my android date picker to shove into a date object.

For example:

public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) 

public void onTimeSet(TimePicker view, int hourOfDay, int minute) 

Those event handlers will give me: 2011, 7, 5 10,30 (if the date was August 5th, 2011 and the time was 10:30) Where do I get Am/Pm in Android?

I'm doing this but its not working right:

Date date = new Date(year,monthOfYear,dayOfMonth,hourOfDay,minute);

I need to accomplish the Android equivalent of this blackberry code. Blackberry date picker graciously provides a date object (rather than raw integers):

public void run() {
            DateTimePicker datePicker = DateTimePicker.createInstance();

            // Set the max time to 24 hours into the future. This allows for selecting clips
            // across time zones, but prevents the user from wandering off into no-mans' land.
            Calendar maxDateTime = Calendar.getInstance();
            maxDateTime.setTime(new Date(System.currentTimeMillis() + 24*3600*1000));
            datePicker.setMaximumDate(maxDateTime);

            if (datePicker.doModal())
            {
                Calendar selectedDate = datePicker.getDateTime();
                Date beforeDate = selectedDate.getTime();
                ClipStore.getInstance().getClips(camera, beforeDate);
            }
        }

Upvotes: 1

Views: 1799

Answers (3)

JB Nizet
JB Nizet

Reputation: 691715

Use a Calendar :

Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, monthOfYear);
cal.set(Calendar.DATE, dayOfMonth);
cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date date = cal.getTime();

The hour of day goes from 0 to 23.

Upvotes: 2

Adam Storm
Adam Storm

Reputation: 724

By stock the Java.util will use Military time. aka 10:30 refers to 10:30 AM. 10:30 pm will be shown as 22:30. If you want to convert it to pm try something like this:

public String ampmChanger (String time) {
  int hour = (int)time.substring(0,2);
  String timeAppendage;
  if (hour > 12) { // For 1 PM and on
    hour -= 12; 
    timeAppendage = " PM"; 
  }
  else if (hour == 12) timeAppendage = " PM"; // For 12 pm
  else timeAppendage = " AM"; // For 0(12AM) to Noon

  return String.valueOf(hour)+time.substring(2)+timeAppendage;
}

Upvotes: 0

Colin O'Dell
Colin O'Dell

Reputation: 8647

I believe that hourOfDay uses 24-hour time, so it should be a value between 0 and 23 inclusive. If it's greater >=12, it's PM.

Upvotes: 0

Related Questions