我必须在两小时之间得到总分。
17:00 and 16.06 hrs
如果我喜欢
17.00-16.06 =0.94
但正确答案 54分钟。
所以从逻辑上讲,我怎样才能从两次获得差异。
不使用Calender api或Joda Time。
代码:
private double getTimeDifference(Date startDate,Date endDate, boolean sameDay)
{
double startTimeF=Double.valueOf(startDate.getHours()+"."+startDate.getMinutes());
double endTimeF=Double.valueOf(endDate.getHours()+"."+endDate.getMinutes());
double totalTime=0;
boolean isCalculated=false;
for(double workTime:timeMap.keySet())
{
double endTimeC=timeMap.get(workTime);
if(startTimeF>=workTime && startTimeF<=endTimeC)
{
if(endTimeF<endTimeC && sameDay)
{
isCalculated=true;
totalTime+=endTimeF-startTimeF;
}
else
{
totalTime+=endTimeC-startTimeF;
}
break;
}
}
for(double workTime:timeMap.keySet())
{
double endTimeC=timeMap.get(workTime);
if(endTimeF>=workTime && endTimeF<=endTimeC)
{
if(!isCalculated)
{
if(workTime<startTimeF && sameDay)
{
totalTime+=endTimeF-startTimeF;
}
else
{
totalTime+=endTimeF-workTime;
}
}
}
else if(!sameDay)
{
totalTime+=endTimeC-workTime;
}
}
return totalTime;
}
时间映射包含json字符串的键和值:
{“time”:[{“startTime”:“8:00”,“endTime”:“12:30”,“type”:“Working”},{“startTime”:“12:31”, “endTime”:“13:00”,“type”:“Break”},{“startTime”:“13:01”,“endTime”:“17:00”,“type”:“Working”}]}
答案 0 :(得分:3)
long milliDifference = date1.getTime() - date2.getTime();
long minuteDifference = TimeUnit.MINUTES.convert(milliDifference, TimeUnit.MILLISECONDS);
其中date1和date2的类型为java.util.Date。
答案 1 :(得分:2)
String firstTime = "17:00";
String secondTime = "16:09";
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
try {
long diff = format.parse(firstTime).getTime() - format.parse(secondTime).getTime();
System.out.println("Difference is " + (diff / (60 * 1000)) + " minutes.");
} catch (ParseException e) {
//Parsing error
}
输出:
Difference is 51 minutes.
答案 2 :(得分:2)
尝试:
String from="17:00";
String to="16:06";
String fromTime[]=from.split(":");
String toTime[]=to.split(":");
int fromMin=Integer.parseInt(fromTime[0])*60+Integer.parseInt(fromTime[1]);
int toMin=Integer.parseInt(toTime[0])*60+Integer.parseInt(toTime[1]);
System.out.println("Difference "+(fromMin-toMin)+" minutes");
答案 3 :(得分:1)
Duration.between( LocalTime.parse( "17:00" ) , LocalTime.parse( "16:06" ) )
麻烦的旧遗留日期时间类现在被java.time类取代。
LocalTime
类代表没有日期且没有时区的时间。
Duration
类跟踪未附加到时间轴的时间跨度。你的17:00和16:06的例子意味着一个负面的持续时间,进入过去。
LocalTime start = LocalTime.parse( "17:00" );
LocalTime stop = LocalTime.parse( "16:06" ); // Going backwards into the past for a negative duration.
Duration duration = Duration.between( start , stop );