确定从 hh:mm:ss 到 hh:mm:ss 的时间是上午、下午还是两者 java
Determine whether time from hh:mm:ss to hh:mm:ss is am,pm, or both java
我有 2 个时间字符串,即 "from" 和 "to" 时间。
示例:
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 个字符串时间和确定符是上午、下午还是两者。
谢谢。
使用 Java 日历 API class 本身。检查以下答案:
java get date marker field(am/pm) ,
Calculate Date/Time Difference in Java considering 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;
}
}
我有 2 个时间字符串,即 "from" 和 "to" 时间。
示例:
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 个字符串时间和确定符是上午、下午还是两者。
谢谢。
使用 Java 日历 API class 本身。检查以下答案: java get date marker field(am/pm) , Calculate Date/Time Difference in Java considering 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;
}
}