我从 JSON 文件中获取一个日期,它是字符串格式的。我有两个字符串值,名为 startdate 和 enddate,它们来自意图到 currentActivity。现在我想检查一下,来自 json 文件的日期值是在 startdate 之后还是 enddate 之前。我怎样才能做到这一点?是的,我 json 文件的格式是“yyyy-mm-dd”。
JSON 数据看起来像:
{"posts":[{"start_date":"2013-02-15","end_date":"2013-02-21"}]}
这是我尝试过的代码,但我得到的输出为Mon Jan 07 00:00:00 GMT+5:30 2013:
Intent intent = getIntent();
String startDate = intent.getStringExtra("startDate"); //I have check this. It is proper.
String endDate = intent.getStringExtra("endDate"); //I have check this. It is proper.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date start = null,end = null;
try {
start = sdf.parse(startDate);
end = sdf.parse(endDate);
} catch (ParseException e1) {
e1.printStackTrace();
}
这是比较日期的代码:
Date date = null;
try {
date = sdf.parse(c.getString(TAG_DATE)); //I am getting the date from a json file here.
} catch (ParseException e) {
e.printStackTrace();
}
Date currDate = new Date();
if (end.compareTo(currDate) < 0 || start.compareTo(currDate) < 0) {
Toast.makeText(getApplicationContext(),"Please select valid dates...",Toast.LENGTH_SHORT).show();
} else if (end.compareTo(currDate) == 0 && start.compareTo(currDate) >= 0){
if (date.after(start)) {
Toast.makeText(getApplicationContext(), "After...",Toast.LENGTH_SHORT).show();
}
} else if (end.compareTo(currDate) > 0 && start.compareTo(currDate) >= 0) {
if (date.after(start) && date.before(end)) {
Toast.makeText(getApplicationContext(),"Before...",Toast.LENGTH_SHORT).show();
}
}