在java中检查当前时间位于两次 [英] Check current time lies in two times in java
问题描述
我正在尝试检查当前时间是否在开始时间和结束时间之间.但是我的方法总是返回false:
I am trying to check whether current time is between Start Time and End time. But my method always return false:
from = "5:10:00";to = "10:10:00"
private boolean isTimeBetweenTwoTime(String from, String to) throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat("H:mm:ss");
Date date_from = formatter.parse(from);
Date date_to = formatter.parse(to);
Time startTime = new Time(date_from.getTime());
Time endTime = new Time(date_to.getTime());
Calendar c = Calendar.getInstance();
Time now = new Time(c.getTimeInMillis());
if (now.before(endTime) && now.after(startTime)) {
Log.d(LOG_TAG, "Yes time between");
return true;
}
return false;
}
推荐答案
问题是当你这样做时
Date date_from = formatter.parse(from);
Date date_to = formatter.parse(to);
并且格式化程序是这样定义的:
and the formatter is so defined:
SimpleDateFormat formatter = new SimpleDateFormat("H:mm:ss");
then 仅适用于与时间相关的 java api,但日期对象包含的不仅仅是时间信息,它们还包含年、月等信息,并且这些信息正在初始化为一个纪元 UNIXTime
then is for the java api relevant only the time, but date objects hold more than time info, they hold too year, month, etc and those are getting initalize to a epoch UNIXTime
所以您创建的初始日期是
so the initial dates you are creating are
欧洲中部时间 1970 年 1 月 1 日星期四 05:10:00 欧洲中部时间 1970 年 1 月 1 日星期四 10:10:00 CET
Thu Jan 01 05:10:00 CET 1970 and Thu Jan 01 10:10:00 CET 1970
所以询问今天/现在(2016 年 6 月 22 日)是否在这些日期之间永远不会返回 true...
so asking if today/right now (22th june 2016) is between those dates will NEVER return true...
另一方面,您的条件看起来是颠倒的,作为最后的提示,您不需要 SQL-Classes 进行计算,只需使用日期对象,您就会得到很好的
on the other hand you conditions look inverted and as final tip you dont need SQL-Classes for the calculation, just with date objects you will get it pretty good
public static void main(String[] args) throws ParseException {
String from = "5:10:00";
String to = "10:10:00";
String n = "08:10:00";
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
Date date_from = formatter.parse(from);
Date date_to = formatter.parse(to);
Date dateNow = formatter.parse(n);
if (date_from.before(dateNow) && date_to.after(dateNow)) {
System.out.println("Yes time between");
}
}
这篇关于在java中检查当前时间位于两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!