java - 如何将时间字符串与当前时间进行比较?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24927701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compare time string with current time in java?
提问by mayank sharma
I have a time string like "15:30" i want to compare that string with the current time. Please suggest something easy. And how to get the current time in hour minute format("HH:mm")
我有一个像“15:30”这样的时间字符串,我想将该字符串与当前时间进行比较。请推荐一些简单的东西。以及如何以小时分钟格式获取当前时间("HH:mm")
采纳答案by Basil Bourque
tl;dr
tl;博士
LocalTime.now()
.isAfter( LocalTime.parse( "15:30" ) )
Details
细节
You should be thinking the other way around: How to get that string turned into a time value. You would not attempt math by turning your numbers into strings. So too with date-time values.
您应该换一种方式思考:如何将该字符串转换为时间值。您不会通过将数字转换为字符串来尝试数学。日期时间值也是如此。
Avoid the old bundled classes, java.util.Date and .Calendar as they are notoriously troublesome, flawed both in design and implementation. They are supplanted by the new java.time packagein Java 8. And java.time was inspired by Joda-Time.
避免使用旧的捆绑类 java.util.Date 和 .Calendar,因为它们是出了名的麻烦,在设计和实现上都有缺陷。他们被新取代java.time包中的Java 8。而 java.time 的灵感来自Joda-Time。
Both java.timeand Joda-Timeoffer a class to capture a time-of-day without any date to time zone: LocalTime
.
无论java.time和乔达时间提供了一个类来捕获时间的天,没有任何日期的时区:LocalTime
。
java.time
时间
Using the java.time classes built into Java, specifically LocalTime
. Get the current time-of-day in your local time zone. Construct a time-of-day per your input string. Compare with the isBefore
, isAfter
, or isEqual
methods.
使用 Java 内置的 java.time 类,特别是LocalTime
. 获取您当地时区的当前时间。根据您的输入字符串构造一天中的时间。与比较isBefore
,isAfter
或isEqual
方法。
LocalTime now = LocalTime.now();
LocalTime limit = LocalTime.parse( "15:30" );
Boolean isLate = now.isAfter( limit );
Better to specify your desired/expected time zone rather than rely implicitly on the JVM's current default time zone.
最好指定您想要/预期的时区,而不是隐式依赖 JVM 的当前默认时区。
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
LocalTime now = LocalTime.now( z ); // Explicitly specify the desired/expected time zone.
LocalTime limit = LocalTime.parse( "15:30" );
Boolean isLate = now.isAfter( limit );
Joda-Time
乔达时间
The code in this case using the Joda-Time library happens to be nearly the same as the code seen above for java.time.
在这种情况下,使用 Joda-Time 库的代码恰好与上面看到的 java.time 代码几乎相同。
Beware that the Joda-Timeproject is now in maintenance mode, with the team advising migration to the java.timeclasses.
请注意Joda-Time项目现在处于维护模式,团队建议迁移到java.time类。
About java.time
关于 java.time
The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
, Calendar
, & SimpleDateFormat
。
The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8, Java SE 9, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- The ThreeTenABPproject adapts ThreeTen-Backport(mentioned above) for Android specifically.
- See How to use ThreeTenABP….
- Java SE 8、Java SE 9及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- 所述ThreeTenABP项目适应ThreeTen-反向移植(上述)为Android特异性。
- 请参阅如何使用ThreeTenABP ...。
The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
该ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如Interval
,YearWeek
,YearQuarter
,和更多。
回答by Darshan Lila
Following would get the time. You can than use it to compare
跟随将得到时间。你可以用它来比较
String currentTime=new SimpleDateFormat("HH:mm").format(new Date());
回答by James
Just compare the strings as normal like so:
只需像平常一样比较字符串:
String currentTime = new SimpleDateFormat("HH:mm").format(new Date());
String timeToCompare = "15:30";
boolean x = currentTime.equals(timeToCompare);
If the times are the same x will be true
if they are not x will be false
如果时间相同 x 将是true
如果它们不同 x 将是false
回答by Ramzan Zafar
Try this
尝试这个
public static String compareTime(String d) {
if (null == d)
return "";
try {
SimpleDateFormat sdf= new SimpleDateFormat("HH:mm");
d = sdf.format(new Date());
} catch (Exception e) {
e.printStackTrace();
}
return d;
}
then you can compare with your string
然后你可以与你的字符串进行比较
回答by Bacteria
I have a similar situation where I need to compare time string like "15:30" with the current time. I am using Java 7so I can not use Basil Bourque's solution. So I have implemented one method which takes one string like "15:30" and check with current time and returns true if current time is after input time.
我有一个类似的情况,我需要将像“15:30”这样的时间字符串与当前时间进行比较。我使用的是Java 7,所以我不能使用 Basil Bourque 的解决方案。所以我实现了一种方法,它接受一个字符串,如 "15:30" 并检查当前时间,如果当前时间在输入时间之后,则返回true。
public static boolean checkSlaMissedOrNot(String sla) throws ParseException {
boolean slaMissedOrnot = false;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(sla.substring(0, 2)));
cal.set(Calendar.MINUTE, Integer.parseInt(sla.substring(3)));
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
if (Calendar.getInstance().after(cal)) {
System.out.println("it's SLA missed");
slaMissedOrnot = true;
} else {
System.out.println("it's fine & not SLA missed");
}
return slaMissedOrnot;
}
Calendar has other use full methods like after(Object when)
日历还有其他使用完整的方法,如 after(Object when)
Returns whether this Calendar represents a time after the time represented by the specified Object. You can use this method also to compare time string with the current time.
返回此 Calendar 是否表示指定对象表示的时间之后的时间。您也可以使用此方法将时间字符串与当前时间进行比较。
回答by Dato' Sapik
Here is my example to compare before and after current time :
这是我比较当前时间前后的示例:
MainActivity.java
主活动.java
Button search = (Button) findViewById(R.id.searchBus);
SimpleDateFormat sdfDate = new SimpleDateFormat("HH:mm");
String limit = "23:00";
Date limitBus=null;
try {
limitBus = sdfDate.parse(limit);
} catch (ParseException e) {
e.printStackTrace();
}
String start = "07:15";
Date startBus=null;
try {
startBus = sdfDate.parse(start);
} catch (ParseException e) {
e.printStackTrace();
}
String user_time = getCurrentTimeStamp();
Date now = null;
try {
now = sdfDate.parse(user_time);
} catch (ParseException e) {
e.printStackTrace();
}
if (now.after(limitBus)||now.before(startBus)){
Toast.makeText(this, "Bus Operation Hours : 7:15AM - 11.00PM", Toast.LENGTH_LONG).show();
search.setEnabled(false);
}
else
{
search.setEnabled(true);
}
//get current time method
public static String getCurrentTimeStamp() {
SimpleDateFormat sdfDate = new SimpleDateFormat("HH:mm");//dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
return strDate;
}
回答by Sc001010tt
So my Solution is a little bit different, Its starts with creating an clock with the current time, and testing the hour agaisnt a user defined int.
所以我的解决方案有点不同,它首先创建一个具有当前时间的时钟,并测试用户定义的 int 小时。
public void TextClockWindow() {
this.pack();
javax.swing.Timer t = new javax.swing.Timer(1000, (ActionEvent e) -> {
Calendar calendar = new GregorianCalendar();
String am_pm;
calendar.setTimeZone(TimeZone.getDefault());
Calendar now = Calendar.getInstance();
int h = now.get(Calendar.HOUR_OF_DAY);
int m = now.get(Calendar.MINUTE);
int s = now.get(Calendar.SECOND);
if (calendar.get(Calendar.AM_PM) == 0) {
am_pm = "AM";
} else {
am_pm = "PM";
} // Code to Determine whether the time is AM or PM
Clock.setText("" + h + ":" + m + " " + am_pm);
if(h < 5) { //int here which tests agaisnt the hour evwery second
System.out.println("Success");
} else {
System.out.println("Failure");
}
});
t.start();
}
回答by Abhishek Sengupta
This code will check User Inputted timewith current system timeand will return time differencein long value.
此代码将检查用户输入的时间与当前系统时间,并以长值返回时间差。
public long getTimeDifferenceInMillis (String dateTime) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long currentTime = new Date().getTime();
long endTime = 0;
try {
//Parsing the user Inputed time ("yyyy-MM-dd HH:mm:ss")
endTime = dateFormat.parse(dateTime).getTime();
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
if (endTime > currentTime)
return endTime - currentTime;
else
return 0;
}
The user should pass the time in "yyyy-MM-dd HH:mm:ss"format.
用户应以“yyyy-MM-dd HH:mm:ss”格式传递时间。