-1

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.

Dimitri
  • 1,924
  • 9
  • 43
  • 65

2 Answers2

2

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;
    }

}
Krzysztof Cichocki
  • 6,294
  • 1
  • 16
  • 32
0

Use the Java Calendar API class itself .. Check the below answers : java get date marker field(am/pm) , Calculate Date/Time Difference in Java considering AM/PM

Community
  • 1
  • 1
sanjay B.
  • 1
  • 1