时间比较

我有一段时间在hh:mm ,它必须由用户以这种格式input。

但是,我想比较一下(例如11:22)是上午10点到下午6点? 但是我怎么比较呢?

Java还没有一个好的内置Time类(它有一个用于JDBC查询,但这不是你想要的)。

一种select是使用JodaTime API和LocalTime类。

坚持只使用内置的Java API,你就坚持使用java.util.Date 。 您可以使用SimpleDateFormatparsing时间,然后使用Date比较函数来查看它是否在其他时间之前或之后:

 SimpleDateFormat parser = new SimpleDateFormat("HH:mm"); Date ten = parser.parse("10:00"); Date eighteen = parser.parse("18:00"); try { Date userDate = parser.parse(someOtherDate); if (userDate.after(ten) && userDate.before(eighteen)) { ... } } catch (ParseException e) { // Invalid date was entered } 

或者你可以使用一些string操作,也许是一个正则expression式来提取小时和分钟的部分,将它们转换为数字并进行数字比较:

 Pattern p = Pattern.compile("(\d{2}):(\d{2})"); Matcher m = p.matcher(userString); if (m.matches() ) { String hourString = m.group(1); String minuteString = m.group(2); int hour = Integer.parseInt(hourString); int minute = Integer.parseInt(minuteString); if (hour >= 10 && hour <= 18) { ... } } 

这完全取决于你想要完成什么。

使用Java 8+,您可以使用新的Java时间API:

  • parsing时间:

     LocalTime time = LocalTime.parse("11:22") 
  • 做date比较,你有LocalTime::isBeforeLocalTime::isAfter – 注意这些方法是严格的

所以你的问题将会如此简单:

 public static void main(String[] args) { LocalTime time = LocalTime.parse("11:22"); System.out.println(isBetween(time, LocalTime.of(10, 0), LocalTime.of(18, 0))); } public static boolean isBetween(LocalTime candidate, LocalTime start, LocalTime end) { return !candidate.isBefore(start) && !candidate.isAfter(end); // Inclusive. } 

对于包容性的开始,但独占的结局(半开放),使用这一行。

 return !candidate.isBefore(start) && candidate.isBefore(end); // Exclusive of end. 

例:

 import java.util.*; import java.lang.Object; import java.text.Collator; public class CurrentTime{ public class CurrentTime { public static void main( String[] args ) { Calendar calendar = new GregorianCalendar(); String am_pm; int hour = calendar.get( Calendar.HOUR ); int minute = calendar.get( Calendar.MINUTE ); // int second = calendar.get(Calendar.SECOND); if( calendar.get( Calendar.AM_PM ) == 0 ){ am_pm = "AM"; if(hour >=10) System.out.println( "welcome" ); } else{ am_pm = "PM"; if(hour<6) System.out.println( "welcome" ); } String time = "Current Time : " + hour + ":" + minute + " " + am_pm; System.out.println( time ); } } 

资源

从你的陈述来看,你似乎只想写:

 if (10 >= hh && hh < 18) { ... } 

如果你已经有足够的时间了,这是微不足道的。 但是,你确实在问别的吗?

 import java.util.Calendar; Calendar cal = Calendar.getInstance(); int currentHour = cal.get(Calendar.HOUR); if (currentHour > 10 && currentHour < 18) { //then rock on } 
 package javaapplication4; import java.text.*; import java.util.*; /** * * @author Stefan Wendelmann */ public class JavaApplication4 { private static SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); /** * @param args the command line arguments */ public static void main(String[] args) throws ParseException { SimpleDateFormat parser = new SimpleDateFormat("dd.MM.YYYY HH:mm:ss.SSS"); Date before = parser.parse("01.10.1990 07:00:00.000"); Date base = parser.parse("01.10.1990 08:00:00.000"); Date after = parser.parse("01.10.1990 09:00:00.000"); printCompare(base, base, "=="); printCompare(base, before, "=="); printCompare(base, before, "<"); printCompare(base, after, "<"); printCompare(base, after, ">"); printCompare(base, before, ">"); printCompare(base, before, "<="); printCompare(base, base, "<="); printCompare(base, after, "<="); printCompare(base, after, ">="); printCompare(base, base, ">="); printCompare(base, before, ">="); } private static void printCompare (Date a, Date b, String operator){ System.out.println(sdf.format(b)+"\t"+operator+"\t"+sdf.format(a)+"\t"+compareTime(a, b, operator)); } protected static boolean compareTime(Date a, Date b, String operator) { if (a == null) { return false; } try { //Zeit aus Datum holen // The Magic happens here i only get the Time out of the Date Object SimpleDateFormat parser = new SimpleDateFormat("HH:mm:ss.SSS"); a = parser.parse(parser.format(a)); b = parser.parse(parser.format(b)); } catch (ParseException ex) { System.err.println(ex); } switch (operator) { case "==": return b.compareTo(a) == 0; case "<": return b.compareTo(a) < 0; case ">": return b.compareTo(a) > 0; case "<=": return b.compareTo(a) <= 0; case ">=": return b.compareTo(a) >= 0; default: throw new IllegalArgumentException("Operator " + operator + " wird für Feldart Time nicht unterstützt!"); } } } 
 run: 08:00:00.000 == 08:00:00.000 true 07:00:00.000 == 08:00:00.000 false 07:00:00.000 < 08:00:00.000 true 09:00:00.000 < 08:00:00.000 false 09:00:00.000 > 08:00:00.000 true 07:00:00.000 > 08:00:00.000 false 07:00:00.000 <= 08:00:00.000 true 08:00:00.000 <= 08:00:00.000 true 09:00:00.000 <= 08:00:00.000 false 09:00:00.000 >= 08:00:00.000 true 08:00:00.000 >= 08:00:00.000 true 07:00:00.000 >= 08:00:00.000 false BUILD SUCCESSFUL (total time: 0 seconds) 

亚当在他的回答中解释得很好但我用这种方式。 我认为这是理解Java中的时间比较的最简单的方法

首先创build3个日历对象,只设置你的时间,小时和分钟。

然后得到那个时间的GMT毫秒,并简单地比较。

防爆。

 Calendar chechDateTime = Calendar.getInstance(); chechDateTime.set(Calendar.MILLISECOND, 0); chechDateTime.set(Calendar.SECOND, 0); chechDateTime.set(Calendar.HOUR, 11); chechDateTime.set(Calendar.MINUTE, 22); Calendar startDateTime = Calendar.getInstance(); startDateTime.set(Calendar.MILLISECOND, 0); startDateTime.set(Calendar.SECOND, 0); startDateTime.set(Calendar.HOUR, 10); startDateTime.set(Calendar.MINUTE, 0); Calendar endDateTime = Calendar.getInstance(); endDateTime.set(Calendar.MILLISECOND, 0); endDateTime.set(Calendar.SECOND, 0); endDateTime.set(Calendar.HOUR, 18); endDateTime.set(Calendar.MINUTE, 22); long chechDateTimeMilliseconds=chechDateTime.getTime().getTime(); long startDateTimeMilliseconds=startDateTime.getTime().getTime(); long endDateTimeMilliseconds=endDateTime.getTime().getTime(); System.out.println("chechDateTime : "+chechDateTimeMilliseconds); System.out.println("startDateTime "+startDateTimeMilliseconds); System.out.println("endDateTime "+endDateTimeMilliseconds); if(chechDateTimeMilliseconds>=startDateTimeMilliseconds && chechDateTimeMilliseconds <= endDateTimeMilliseconds ){ System.out.println("In between "); }else{ System.out.println("Not In between "); } 

输出将如下所示:

 chechDateTime : 1397238720000 startDateTime 1397233800000 endDateTime 1397263920000 In between 

以下假设您的小时和分钟分别存储在名为hhmmvariables中。

 if ((hh > START_HOUR || (hh == START_HOUR && mm >= START_MINUTE)) && (hh < END_HOUR || (hh == END_HOUR && mm <= END_MINUTE))) { ... } 

我使用这个类的时间格式为“hh:mm:ss”,你可以在你的例子中使用“hh:mm:00”(零秒)。 这是完整的代码。 它比较和function之间也检查时间格式(在无效的时间和抛出TimeException的情况下)。 希望您可以使用它或修改它以满足您的需求。

时间等级:

 package es.utility.time; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author adrian */ public class Time { private int hours; //Hours of the day private int minutes; //Minutes of the day private int seconds; //Seconds of the day private String time; //Time of the day /** * Constructor of Time class * * @param time * @throws TimeException if time parameter is not valid */ public Time(String time) throws TimeException { //Check if valid time if (!validTime(time)) { throw new TimeException(); } //Init class parametars String[] params = time.split(":"); this.time = time; this.hours = Integer.parseInt(params[0]); this.minutes = Integer.parseInt(params[1]); this.seconds = Integer.parseInt(params[2]); } /** * Constructor of Time class * * @param hours * @param minutes * @param seconds * @throws TimeException if time parameter is not valid */ public Time(int hours, int minutes, int seconds) throws TimeException { //Check if valid time if (!validTime(hours, minutes, seconds)) { throw new TimeException(); } this.time = timeToString(hours, minutes, seconds); this.hours = hours; this.minutes = minutes; this.seconds = seconds; } /** * Checks if the sting can be parsed as time * * @param time (correct from hh:mm:ss) * @return true if ok <br/> false if not ok */ private boolean validTime(String time) { String regex = "([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(time); return m.matches(); } /** * Checks if the sting can be parsed as time * * @param hours hours * @param minutes minutes * @param seconds seconds * @return true if ok <br/> false if not ok */ private boolean validTime(int hours, int minutes, int seconds) { return hours >= 0 && hours <= 23 && minutes >= 0 && minutes <= 59 && seconds >= 0 && seconds <= 59; } /** * From Integer values to String time * * @param hours * @param minutes * @param seconds * @return String generated from int values for hours minutes and seconds */ private String timeToString(int hours, int minutes, int seconds) { StringBuilder timeBuilder = new StringBuilder(""); if (hours < 10) { timeBuilder.append("0").append(hours); } else { timeBuilder.append(hours); } timeBuilder.append(":"); if (minutes < 10) { timeBuilder.append("0").append(minutes); } else { timeBuilder.append(minutes); } timeBuilder.append(":"); if (seconds < 10) { timeBuilder.append("0").append(seconds); } else { timeBuilder.append(seconds); } return timeBuilder.toString(); } /** * Compare this time to other * * @param compare * @return -1 time is before <br/> 0 time is equal <br/> time is after */ public int compareTime(Time compare) { //Check hours if (this.getHours() < compare.getHours()) { //If hours are before return -1 return -1; } if (this.getHours() > compare.getHours()) { //If hours are after return 1 return 1; } //If no return hours are equeal //Check minutes if (this.getMinutes() < compare.getMinutes()) { //If minutes are before return -1 return -1; } if (this.getMinutes() > compare.getMinutes()) { //If minutes are after return 1 return 1; } //If no return minutes are equeal //Check seconds if (this.getSeconds() < compare.getSeconds()) { //If minutes are before return -1 return -1; } if (this.getSeconds() > compare.getSeconds()) { //If minutes are after return 1 return 1; } //If no return seconds are equeal and return 0 return 0; } public boolean isBetween(Time before, Time after) throws TimeException{ if(before.compareTime(after)== 1){ throw new TimeException("Time 'before' is after 'after' time"); } //Compare with before and after if (this.compareTime(before) == -1 || this.compareTime(after) == 1) { //If time is before before time return false or time is after after time return false; } else { return true; } } public int getHours() { return hours; } public void setHours(int hours) { this.hours = hours; } public int getMinutes() { return minutes; } public void setMinutes(int minutes) { this.minutes = minutes; } public int getSeconds() { return seconds; } public void setSeconds(int seconds) { this.seconds = seconds; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } /** * Override the toString method and return all of the class private * parameters * * @return String Time{" + "hours=" + hours + ", minutes=" + minutes + ", * seconds=" + seconds + ", time=" + time + '}' */ @Override public String toString() { return "Time{" + "hours=" + hours + ", minutes=" + minutes + ", seconds=" + seconds + ", time=" + time + '}'; } } 

TimeException类:

 package es.utility.time; /** * * @author adrian */ public class TimeException extends Exception { public TimeException() { super("Cannot create time with this params"); } public TimeException(String message) { super(message); } }