【发布时间】:2018-11-22 15:56:58
【问题描述】:
我正在使用 JSON 文件来存储会议的多个条目。我正在尝试在 Java 的 Calendar 对象中获取使用 date.before 和 date.after 的当前事件。我当前的代码正在返回三个不同的事件,我不知道,我想知道有人对我尝试过的所有事情有任何建议。我将在下面附上 JSON 和代码。我还将附上代码放入控制台窗口的内容。
控制台日志
11-22 15:54:12.883 5797-5797/reloaded D/timetest:
add event with name:Coffee Break
time start: Tue Nov 22 15:30:00 GMT+00:00 18
time end: Wed Nov 23 16:30:00 GMT+00:00 18
time now: Wed Nov 23 15:45:00 GMT+00:00 18
11-22 15:54:12.885 5797-5797/reloaded D/timetest:
add event with name:Panel Discussion
time start: Tue Nov 22 16:30:00 GMT+00:00 18
time end: Wed Nov 23 17:15:00 GMT+00:00 18
time now: Wed Nov 23 15:45:00 GMT+00:00 18
11-22 15:54:12.888 5797-5797/reloaded D/timetest:
add event with name:Turning Information into an Engaging Experience – The Design of Media Spaces
time start: Tue Nov 22 17:15:00 GMT+00:00 18
time end: Wed Nov 23 18:00:00 GMT+00:00 18
time now: Wed Nov 23 15:45:00 GMT+00:00 18
JSON
{
"eventid": "11",
"roomid": "9",
"type": "other",
"name": "Coffee Break",
"timestart": "15:30",
"timeend": "16:30",
"day": "1",
"text": "Discover the Future Forum",
"pic": "coffeecup.png",
"speakerid": "1",
"speaker": ""
},
{
"eventid": "12",
"roomid": "9",
"type": "other",
"name": "Panel Discussion",
"timestart": "16:30",
"timeend": "17:15",
"day": "1",
"text": "",
"pic": "welcometalk.png",
"speakerid": "1",
"speaker": "fudged"
},
{
"eventid": "13",
"roomid": "9",
"type": "lecture",
"name": "Turning Information into an Engaging Experience – The Design of Media Spaces",
"timestart": "17:15",
"timeend": "18:00",
"day": "1",
"text": "fdsfsd",
"pic": "p4.jpg",
"speakerid": "6",
"speaker": "test"
},
Java
try {
String string1 = "22/11/18 " + c.getString("timestart");
Date time1 = new SimpleDateFormat("dd/MM/yyyy HH:mm").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
String string2 = "22/11/18 " + c.getString("timeend");
Date time2 = new SimpleDateFormat("dd/MM/yyyy HH:mm").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
String someRandomTime = "22/11/18 15:45";
Date d = new SimpleDateFormat("dd/MM/yyyy HH:mm").parse(someRandomTime);
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(d);
calendar3.add(Calendar.DATE, 1);
Date now = calendar3.getTime();
Date timestart = calendar1.getTime();
Date timeend = calendar2.getTime();
if ((now.after(timestart)) && (now.before(timeend))) {
Log.d("timetest","add event with name:"+c.getString("name") + " time start: " + timestart+ " time end " + timeend + " time now " + now);
}
}
catch (ParseException e) {
e.printStackTrace();
}
【问题讨论】:
-
1.尝试记录日历对象以查看时间是否正确解析。 2.您也可以直接比较日历对象,而不是转换为日期。
-
我确实做了一些日志,我附上了@viv
-
你到底想做什么?
-
您不应再使用
Date和Calendar类。使用它们很麻烦。请改用新的 Java 日期和时间 API。如果由于您的 Android 版本而无法使用,您可以使用 ThreeTen Backport。 -
这可能不是 OP 当前编写的此类代码的最大问题,但如果您要构建更大一点的应用程序,它可能会节省您的时间。 Here's a list of issues with these classes.
标签: java android simpledateformat android-calendar