簡體   English   中英

確定從hh:mm:ss到hh:mm:ss的時間是am,pm還是兩者都為java

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

我有2個時間字符串,即“從”到“到”時間。

例:

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

我如何使用日歷格式確定從開始到開始的時間是下午還是下午。

我的工作:

我有時間:

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 Calendar API類本身。檢查以下答案: java獲取日期標記字段(am / pm)考慮AM / PM計算Java中的日期/時間差

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM