问题的上下文有点轻。你想使用一个线程,你想被提醒......?
但是,作为一个基本示例,您可以执行类似...
// The time we want the alert...
String time = "16:00";
// The date String of now...
String date = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
try {
// The date + time to give us context
Date timeAt = sdf.parse(date + " " + time);
boolean rollOver = false;
// Determine if the time has already passed, if it has
// we need to roll the date to the next day...
if (timeAt.before(new Date())) {
rollOver = true;
}
// A Calendar with which we can manipulate the date/time
Calendar cal = Calendar.getInstance();
cal.setTime(timeAt);
// Skip 15 minutes in advance
cal.add(Calendar.MINUTE, 15);
// Do we need to roll over the time...
if (rollOver) {
cal.add(Calendar.DATE, 1);
}
// The date the alert should be raised
Date alertTime = cal.getTime();
System.out.println("Raise alert at " + alertTime);
// The timer with which we will wait for the alert...
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("duha");
}
}, alertTime);
} catch (ParseException ex) {
}
现在,在你抱怨之前Date
,一切都是相对的。没有Date
时间,我们很难知道什么时候应该提高警惕。这Date
只是帮助我们确定何时应该发出警报......
额外的
上下文就是一切,例如......如果我们使用以下......
String time = "16:00";
try {
Date timeAt = new SimpleDateFormat("HH:mm").parse(time);
System.out.println(timeAt);
} catch (ParseException ex) {
ex.printStackTrace();
}
timeAt
值 be ,这Thu Jan 01 16:00:00 EST 1970
真的没用,时间总是在现在之前......
相反,如果我们使用类似...
String time = "16:00";
String date = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
try {
Date timeAt = new SimpleDateFormat("dd/MM/yyyy HH:mm").parse(date + " " + time);
System.out.println(timeAt);
} catch (ParseException ex) {
ex.printStackTrace();
}
现在的timeAt
遗嘱Thu Sep 05 16:00:00 EST 2013
为我们提供了一些背景信息now
现在,如果我们Calendar
将时间提前 15 分钟...
Calendar cal = Calendar.getInstance();
cal.setTime(timeAt);
cal.add(Calendar.MINUTE, 15);
Date checkTime = cal.getTime();
System.out.println(checkTime);
checkTime
成为Thu Sep 05 16:15:00 EST 2013
. _ 我使用Calendar
它是因为它会在需要时自动为我滚动小时和日期...
这现在允许我们开始使用默认可用的 API 功能。因为毫秒几乎不可能匹配,所以我会被迫做类似的事情......
Calendar watchFor = Calendar.getInstance();
watchFor.setTime(timeAt);
watchFor.set(Calendar.MILLISECOND, 0);
watchFor.set(Calendar.SECOND, 0);
Calendar now = Calendar.getInstance();
now.setTime(new Date());
now.set(Calendar.MILLISECOND, 0);
now.set(Calendar.SECOND, 0);
if (watchFor.equals(now)) {
System.out.println("Go for it...");
}
将毫秒和秒归零,这样我就可以单独比较日期和时间 (HH:mm)。
您当然也可以直接比较毫秒...