我想计算同一周两天(例如周五和周六)之间的时差。验证我的项目的时间限制需要进行这种计算。要了解有关限制的更多信息,请参阅以下示例,
示例 1
{
"id": "3",
"from_day": "Fri",
"from_time": "16:00:00",
"to_day": "Sat",
"to_time": "06:00:00"
}
示例 2
{
"id": "4",
"from_day": "Mon",
"from_time": "04:00:00",
"to_day": "Mon",
"to_time": "09:00:00"
}
根据上面的示例,我必须验证正在运行的应用程序是否在同一周的确切日期和时间之间经过。
到目前为止我做了什么?
我创建了这个简单的函数,它采用“星期几”(例如星期一)、“从时间”(例如04:00:00)和“到时间”例如 09:00:00 作为参数,如果在范围内则返回。
public boolean getValidity(String day, String dateStart, String dateStop) {
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
String current_day = new SimpleDateFormat("EE", Locale.ENGLISH)
.format(date.getTime());
if (current_day.matches(day)) {
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("GMT+8"));
Date today = Calendar.getInstance().getTime();
String datePresent = format.format(today);
Date d1 = null;
Date d2 = null;
Date d3 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
d3 = format.parse(datePresent);
} catch (Exception e) {
e.printStackTrace();
}
long current_time = d3.getTime();
long start_time = d1.getTime();
long stop_time = d2.getTime();
if (current_time >= start_time && current_time <= stop_time) {
return true;
} else {
return false;
}
}
return false;
}
// this function is used for converting the time into GMT +8 before passing as a parameter in the getValidity() function
public String toGMT(String time){
//first convert the received string to date
Date date = null;
//creating DateFormat for converting time from local timezone to GMT
DateFormat format = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
try {
date = format.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
//getting GMT timezone, you can get any timezone e.g. UTC
format.setTimeZone(TimeZone.getTimeZone("GMT+8"));
return format.format(date).toString();
}
但是上面的代码不适用于日期不同的第一个示例。如果有人能提供一些解决问题的想法,那将非常有帮助。
最佳答案
可以将日期对象转为long(自1970年1月1日起的毫秒数),然后使用TimeUnit获取秒数:
long diffInMs = endDate.getTime() - startDate.getTime();
long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMs);
结束日期和开始日期作为您可以自行完成的日期对象。
关于java - 在Android上计算本周两天之间的时差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32393754/