我需要比较当前时间是否在X+30
和X-30
之间。
一切顺利,时间戳,但比较年份设定为1970年;所以输出不准确。
String string1 = "04:41 PM";
Calendar calendar1,calendar2,calendar3,calendar4 ;
DateFormat time1;
Date time;
try {
time1 =new SimpleDateFormat("hh:mm a");
time = time1.parse(string1);
calendar1 = Calendar.getInstance();
calendar1.setTime(time);
System.out.println(time1.format(calendar1.getTime()));
calendar2 = Calendar.getInstance();
calendar2.setTime(time);
calendar2.add(Calendar.MINUTE,30);
System.out.println(time1.format(calendar2.getTime()));
calendar3 = Calendar.getInstance();
calendar3.setTime(time);
calendar3.add(Calendar.MINUTE,-30);
System.out.println(time1.format(calendar3.getTime()));
calendar4=Calendar.getInstance();
System.out.println(time1.format(calendar4.getTime()));
Date now = calendar4.getTime();
if (now.after(calendar3.getTime()) && now.before(calendar2.getTime())) {
//checkes whether the current time is between 14:49:00 and 20:11:13.
System.out.println(true);
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
答案 0 :(得分:1)
hh:mm a
格式YEAR
字段为set to 1970 by default。
Unix时间或POSIX时间是用于描述时间点的系统, 定义为自午夜起来以来经过的秒数 1970年1月1日的协调世界时(UTC),不计算飞跃 秒。
因此,在您的情况下,您希望在比较日期时忽略YEAR
,MONTH
和DAY_OF_MONTH
字段,这样做(这会重置YEAR
,{{1} }和MONTH
字段):
DAY_OF_MONTH
之后:
calendar4.setTime(time1.parse(time1.format(calendar4.getTime())));