简体   繁体   中英

Determine whether time from hh:mm:ss to hh:mm:ss is am,pm, or both java

I have 2 time string ie "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;
    }

}

使用Java Calendar API类本身。检查以下答案: java获取日期标记字段(am / pm)考虑AM / PM计算Java中的日期/时间差

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM