我试图建立一个机制来计算两个日期对象之间的差异,但我遇到了问题。 我将转换为Date对象的第一个输入是:
Ma 14:00
这意味着'周一14:00'我使用以下代码将此字符串转换为日期对象。
try {
date = new SimpleDateFormat("EE HH:mm", Locale.getDefault()).parse(msg);
Log.i("intent", "Date: " + date);
} catch (ParseException e) {
e.printStackTrace();
}
如果我打印Date对象,那么它是          我只对日期名称和时间感兴趣,所以我没有打扰更改日期对象的其他部分。
我的问题如下:我需要知道现在的日子(例如:星期四)和上面的日子(例如:星期一)之间的区别。
我尝试执行以下操作:
Date dateNow = new Date();
dateNow.setHours(date.getHours());
dateNow.setMinutes(date.getMinutes());
dateNow.setSeconds(date.getSeconds());
dateNow.setYear(70);
dateNow.setMonth(0);
Log.i("DAYS TAG", ""+dateNow);
long diff = date.getTime() - dateNow.getTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
Log.i("DAYS TAG", ""+days);
这种方式没有成功,因为我正在处理这些日子,但这些日子是消极的,有时甚至不准确。
基本上我想要的是:
通过这些步骤,我发现了这一点:
Calendar now = Calendar.getInstance();
int weekday = now.get(Calendar.DAY_OF_WEEK);
if(weekday != Calendar.MONDAY){
int days = (Calendar.SATURDAY - weekday + 2) %7;
now.add(Calendar.DAY_OF_YEAR, days);
}
这是即将到来的星期一的日期。就像我想要的第一步一样。然而,当我添加旧日期时,它再也没有工作。它给了错误的约会对象。更新的代码是:
//get difference in days between now and date object.
Calendar old = Calendar.getInstance();
old.setTime(date);
Log.i("...",""+old.get(Calendar.DAY_OF_WEEK));
Calendar now = Calendar.getInstance();
int weekday = now.get(Calendar.DAY_OF_WEEK);
if(weekday != Calendar.MONDAY){
int days = (Calendar.SATURDAY - weekday + 2) %7;
now.add(Calendar.DAY_OF_YEAR, days);
}
Date date2 = now.getTime();
Log.i("tag", ""+date2);
但正如我所说,它给出了错误的日期。
如果有人愿意,我会非常感激。因为我已经在这上面工作了几个小时。
答案 0 :(得分:0)
因为这个问题不重复,所以我会在这里粘贴我的解决方案。
String upcomingAlarmString = Settings.System.getString(getActivity().getContentResolver(),
Settings.System.NEXT_ALARM_FORMATTED);
Calendar tempDate = Calendar.getInstance();
try{
SimpleDateFormat format = new SimpleDateFormat("EE HH:mm", Locale.getDefault());
tempDate.setTime(format.parse(upcomingAlarmString));
} catch (ParseException e){
e.printStackTrace();
}
Calendar alarmDate = Calendar.getInstance();
while(alarmDate.get(Calendar.DAY_OF_WEEK) != tempDate.get(Calendar.DAY_OF_WEEK)){
if(alarmDate.get(Calendar.DAY_OF_WEEK)==7)
alarmDate.set(Calendar.WEEK_OF_YEAR, alarmDate.get(Calendar.WEEK_OF_YEAR) + 1);
alarmDate.set(Calendar.DAY_OF_WEEK, alarmDate.get(Calendar.DAY_OF_WEEK)+1);
}
alarmDate.set(Calendar.HOUR, tempDate.get(Calendar.HOUR));
alarmDate.set(Calendar.MINUTE, tempDate.get(Calendar.MINUTE));
alarmDate.set(Calendar.SECOND, 0);
System.out.println("alarmDate: " + alarmDate.getTime());
System.out.println("calculate difference between alarmDate and now = number of days extra");
正如您所看到的,我使用while循环来获取正确的日期。