确定HH:MM:SS到HH:MM:SS的时间是AM,PM还是Java



我有2个时间字符串,即从"one_answers"到"时间"。

示例:

String from= "05:30:22";
String to ="14:00:22";

我如何确定从到值的时间是am pm还是使用日历格式。

我的工作:

我得到了时间:

agenda_from_hour = Integer.valueOf(from.substring(0, 2));
agenda_to_hour = Integer.valueOf(to .substring(0, 2));

然后

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
                }

问题是当我有时间从6:00:00到12:30:44的时间时,AM是输出。

是否有更好的方法比较2个字符串时间和确定器是AM,PM还是两者兼而有之。

谢谢。

尝试以下:

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日历API类本身。.检查以下答案:Java获取日期标记字段(AM/PM),计算Java的日期/时间差,考虑AM/PM

最新更新