如何比较当前时间与时间范围? [英] How to compare current time with time range?
本文介绍了如何比较当前时间与时间范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个字符串变量 - time1
和 time2
。两者都包含 HH:MM 格式的值。我如何查询:
I have two String variables - time1
and time2
. Both contain value in the format HH:MM. How can I check:
- 如果当前时间在
time1
和time2?
-
time1
将在最近的$ b $内发生b小时?
- If the current time is within
time1
andtime2?
time1
will happen in the nearest hour?
更新。
我已实施以下内容转换 time1
到日期
格式。但它使用折旧方法:
Upd.
I've implemented the following to convert time1
to Date
format. But it uses depreciated methods:
Date clTime1 = new Date();
SimpleDateFormat timeParser = new SimpleDateFormat("HH:mm", Locale.US);
try {
clTime1 = timeParser.parse(time1);
} catch (ParseException e) {
}
Calendar now = Calendar.getInstance();
clTime1.setYear(now.get(Calendar.YEAR) - 1900);
clTime1.setMonth(now.get(Calendar.MONTH));
clTime1.setDate(now.get(Calendar.DAY_OF_MONTH));
System.out.println(clTime1.toString());
推荐答案
- 转换两个字符串到
日期
对象(也是时间对象)
创建一个新的日期
对象。 - 这将是
包含当前时间。 - 使用
Date.before()和Date.after()方法确定
是否在时间间隔内。 - Convert the two strings to
Date
objects (which are also time objects) Create a newDate
object. - This will contain the current time.
- Use the Date.before() and Date.after() methods to determine if you are in the time interval.
编辑:你应该可以直接使用它(并且没有弃用的方法)
You should be able to use this directly (and no deprecated methods)
public static final String inputFormat = "HH:mm";
private Date date;
private Date dateCompareOne;
private Date dateCompareTwo;
private String compareStringOne = "9:45";
private String compareStringTwo = "1:45";
SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);
private void compareDates(){
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR);
int minute = now.get(Calendar.MINUTE);
date = parseDate(hour + ":" + minute);
dateCompareOne = parseDate(compareStringOne);
dateCompareTwo = parseDate(compareStringTwo);
if ( dateCompareOne.before( date ) && dateCompareTwo.after(date)) {
//yada yada
}
}
private Date parseDate(String date) {
try {
return inputParser.parse(date);
} catch (java.text.ParseException e) {
return new Date(0);
}
}
这篇关于如何比较当前时间与时间范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文