Weal Infotech Weal Infotech - 4 years ago 164
Java Question

How to set 12 hours format in time picker with AM & PM?

I want to store a time in only 12 hours format.

the Time Picker is working perfectly but i just want to set AM or PM after the selected time in EditText.

this is my TimePicker theme

Here, my complete code

starttime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Initialize a new time picker dialog fragment
DialogFragment dFragment = new TimePickerFragment();

// Show the time picker dialog fragment
dFragment.show(getActivity().getFragmentManager(),"Time Picker");

}
});


TimePickerDialog.java

package com.Weal.sachin.omcom;

/**
* Created by sachin on 2/1/2017.
*/

import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.widget.TextView;
import android.app.DialogFragment;
import android.app.Dialog;
import java.util.Calendar;
import android.widget.TimePicker;

public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener{

@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
// Get a Calendar instance
final Calendar calendar = Calendar.getInstance();
// Get the current hour and minute
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);

/*
Creates a new time picker dialog with the specified theme.

TimePickerDialog(Context context, int themeResId,
TimePickerDialog.OnTimeSetListener listener,
int hourOfDay, int minute, boolean is24HourView)
*/

// TimePickerDialog Theme : THEME_DEVICE_DEFAULT_LIGHT
TimePickerDialog tpd = new TimePickerDialog(getActivity(),
AlertDialog.THEME_DEVICE_DEFAULT_LIGHT,this,hour,minute,false);

// TimePickerDialog Theme : THEME_DEVICE_DEFAULT_DARK
TimePickerDialog tpd2 = new TimePickerDialog(getActivity(),
AlertDialog.THEME_DEVICE_DEFAULT_DARK,this,hour,minute,false);

// TimePickerDialog Theme : THEME_HOLO_DARK
TimePickerDialog tpd3 = new TimePickerDialog(getActivity(),
AlertDialog.THEME_HOLO_DARK,this,hour,minute,false);

// TimePickerDialog Theme : THEME_HOLO_LIGHT
TimePickerDialog tpd4 = new TimePickerDialog(getActivity(),
AlertDialog.THEME_HOLO_LIGHT,this,hour,minute,false);

// TimePickerDialog Theme : THEME_TRADITIONAL
TimePickerDialog tpd5 = new TimePickerDialog(getActivity(),
AlertDialog.THEME_TRADITIONAL,this,hour,minute,false);

// Return the TimePickerDialog
return tpd;
}

public void onTimeSet(TimePicker view, int hourOfDay, int minute){
// Do something with the returned time
TextView tv = (TextView) getActivity().findViewById(R.id.start_time);
tv.setText( hourOfDay + ":" + minute );

}
}

Answer Source

use this logic to find am pm

public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    String AM_PM ;
    if(hourOfDay < 12) {
        AM_PM = "AM";
    } else {
        AM_PM = "PM";
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download