显然,Java中已经有关于用时间计算的线程。
不过,我的问题再深入一点。我想做的是:
举个例子:
保罗4:00开始工作,9:00结束我希望它返回6:30 (4 + (9-4)/2)
我的代码还没有:
for (int i = 1, n = licenseplateList.size(); i < n; i++)
{
//first look at whether it is considered as day or night time
try {
String time1 = begintimeList.get(i);
String time2 = endingtimeList.get(i);
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long average = ((date2.getTime() - date1.getTime())/2);
System.out.println(average);
}catch (Exception e) {
}
编辑:
我还想知道后来我如何决定它是白天还是晚上(我想使用开始+结束,因为如果超过18:00,我会考虑它接近时间)。但是,我如何在in语句中做到这一点呢?
发布于 2018-05-17 20:49:42
这种计算更容易使用Java8TimeAPI(不是很新的)
public static void main(String[] args) {
String time1Str = "04:00";
String time2Str = "09:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
LocalTime time1 = LocalTime.parse(time1Str, formatter);
LocalTime time2 = LocalTime.parse(time2Str, formatter);
Duration duration = Duration.between(time1, time2); // 9-4
Duration halfDuration = duration.dividedBy(2); // divided by 2
LocalTime result = LocalTime.from(halfDuration.addTo(time1)); // added to start time
System.out.println(result.format(formatter));
}
编辑:跨日期边界的支持范围
在这种情况下,我们需要增加日期价值的时间。这将告诉Java,22:00到01:00的范围大约是“明天”:
public static void main(String[] args) {
String time1Str = "22:00";
String time2Str = "01:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
LocalTime time1 = LocalTime.parse(time1Str, formatter);
LocalTime time2 = LocalTime.parse(time2Str, formatter);
// add date value: start with today
LocalDate today = LocalDate.now();
// combine date time for lower value: will be assigned to today
LocalDateTime dateTime1 = LocalDateTime.of(today, time1);
// combine date time for upper value: will be assigned same day if it is after lower value
// otherwise (we crossed date boundary) assign it to tomorrow
LocalDateTime dateTime2 = time2.isAfter(time1) ?
LocalDateTime.of(today, time2) : LocalDateTime.of(today.plusDays(1), time2);
Duration duration = Duration.between(dateTime1, dateTime2);
Duration halfDuration = duration.dividedBy(2);
LocalTime result = LocalTime.from(halfDuration.addTo(time1));
System.out.println(result.format(formatter));
}
https://stackoverflow.com/questions/50399950
复制相似问题