之前,采用拼接字符串的形式,不断地在Date类型和Long类型之间转换,实在是太过于麻烦,后来采取了这种思路:假设我们将22:00 ~ 10:00 视为夜间时间,则我们先计算出10:00 相对于当天的分钟数,22:00 相对于当天的分钟数,然后将我们取到的Date转换成Long型,加上8 * 60 * 60 * 1000,对 一天的分钟数取余,根据结果来判断是在白天还是夜晚,while循环中继续累加下一分钟,下面见具体算法
package com.company; import com.sun.scenario.Settings; import java.io.File; import java.io.IOException; import java.net.URL; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.regex.Pattern; public class Main { public static void main(String[] args) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date startOrderTime = sdf.parse("2018-05-23 14:00:00"); Date endOrderTime = sdf.parse("2018-05-24 14:36:28"); String staN = "22:00:00"; String etaN = "10:00:00"; new Main().calcRoughly(startOrderTime, endOrderTime, staN, etaN); } private void calcRoughly(Date startOrderTime, Date endOrderTime, String startTimeAtNight, String endTimeAtNight) { // 以分钟为单位进行统计 long dayTime = 0; long nightTime = 0; long startTime = startOrderTime.getTime(); long endTime = endOrderTime.getTime(); long startCurMinutes = calcCurMinutes(startTimeAtNight); long endCurMinutes = calcCurMinutes(endTimeAtNight); while (startTime <= endTime) { long modTime = ((startTime + 8 * 60 * 60 * 1000) / (1000 * 60)) % (24 * 60); if (modTime >= endCurMinutes && modTime < startCurMinutes) { dayTime += 1; } else { nightTime += 1; } startTime += (1000 * 60); } System.out.println(dayTime); System.out.println(nightTime); } // 时间字符串 "22:00:00" long calcCurMinutes(String time) { String pattern = "\\d{2}:\\d{2}:\\d{2}"; if (Pattern.matches(pattern, time)) { int hour = Integer.valueOf(time.substring(0, 2)); int minutes = Integer.valueOf(time.substring(3, 5)); return hour * 60 + minutes; } return 0; } }