I have 2 time string i.e. "from" and "to" time.
Example:
String from= "05:30:22";
String to ="14:00:22";
How can i determine if the time from to to value is am pm or both using calendar format.
My workings :
I get the hour:
agenda_from_hour = Integer.valueOf(from.substring(0, 2));
agenda_to_hour = Integer.valueOf(to .substring(0, 2));
then
if (agenda_from_hour>=12&&agenda_to_hour<=24){
//pm
} else if (agenda_from_hour>=0&&agenda_to_hour<=12){
//am
} else {
//am and pm
}
The problem is when i have time from 6:00:00 to 12:30:44, am is the output.
Is there a better way to compare 2 strings time and determiner whether it is am,pm or both.
Thanks.
try this:
public static void main(String[] args) throws ParseException {
String from= "05:30:22";
String to ="14:00:22";
boolean fromIsAM = isAM(from);
boolean toIsAM = isAM(to);
}
/**
* Return true if the time is AM, false if it is PM
* @param HHMMSS in format "HH:mm:ss"
* @return
* @throws ParseException
*/
public static boolean isAM(String HHMMSS) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date date = sdf.parse(HHMMSS);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(date);
int AM_PM = gc.get(Calendar.AM_PM);
if (AM_PM==0) {
return true;
} else {
return false;
}
}