Java根據(jù)MM-dd和HH:mm格式日期計(jì)算時(shí)長(zhǎng)與大小比較
1.如何根據(jù)多個(gè)"MM-dd"格式的日期(可能跨年)來(lái)計(jì)算總時(shí)長(zhǎng)
特別處理當(dāng)日和次日的情況
解決方案
方法思路
- 將輸入的"MM-dd"格式轉(zhuǎn)換為完整的日期(考慮跨年情況)
- 對(duì)日期進(jìn)行排序
- 計(jì)算相鄰日期之間的時(shí)間差
- 累加得到總時(shí)長(zhǎng)
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
public class DateDurationCalculator {
// 主計(jì)算方法
public static Duration calculateTotalDuration(List<String> monthDayStrings, LocalDate today) {
if (monthDayStrings == null || monthDayStrings.isEmpty()) {
return Duration.ZERO;
}
// 轉(zhuǎn)換所有日期為L(zhǎng)ocalDate(處理跨年)
List<LocalDate> dates = convertMonthDayToDates(monthDayStrings, today);
// 對(duì)日期進(jìn)行排序
Collections.sort(dates);
// 計(jì)算總時(shí)長(zhǎng)
Duration totalDuration = Duration.ZERO;
for (int i = 0; i < dates.size() - 1; i++) {
LocalDate start = dates.get(i);
LocalDate end = dates.get(i + 1);
// 計(jì)算兩個(gè)日期之間的天數(shù)
long daysBetween = ChronoUnit.DAYS.between(start, end);
// 如果日期連續(xù)(當(dāng)日和次日)
if (daysBetween == 1) {
totalDuration = totalDuration.plus(Duration.ofDays(1));
} else {
// 非連續(xù)日期,只計(jì)算單個(gè)日期
totalDuration = totalDuration.plus(Duration.ofDays(1));
}
}
// 加上最后一個(gè)日期
return totalDuration.plus(Duration.ofDays(1));
}
// 將MM-dd轉(zhuǎn)換為L(zhǎng)ocalDate,處理跨年情況
private static List<LocalDate> convertMonthDayToDates(List<String> monthDayStrings, LocalDate today) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");
List<LocalDate> dates = new ArrayList<>();
for (String monthDay : monthDayStrings) {
MonthDay md = MonthDay.parse(monthDay, formatter);
// 獲取可能的年份(今年或明年)
LocalDate date = md.atYear(today.getYear());
if (date.isBefore(today)) {
// 如果日期已經(jīng)過(guò)去,則認(rèn)為是明年
date = md.atYear(today.getYear() + 1);
}
dates.add(date);
}
return dates;
}
public static void main(String[] args) {
// 示例使用
LocalDate today = LocalDate.now();
List<String> dates = Arrays.asList("12-25", "12-26", "01-01", "01-02");
Duration duration = calculateTotalDuration(dates, today);
System.out.println("總天數(shù): " + duration.toDays());
System.out.println("總小時(shí)數(shù): " + duration.toHours());
}
}關(guān)鍵點(diǎn)說(shuō)明
1.跨年處理:
- 使用
MonthDay類解析"MM-dd"格式 - 比較日期與當(dāng)前日期,決定使用今年還是明年的年份
2.當(dāng)日和次日判斷:
- 使用
ChronoUnit.DAYS.between()計(jì)算日期差 - 差值為1表示是連續(xù)的當(dāng)日和次日
3.總時(shí)長(zhǎng)計(jì)算:
- 連續(xù)日期計(jì)算為完整時(shí)間段
- 非連續(xù)日期單獨(dú)計(jì)算
4.輸出結(jié)果:可以獲取總天數(shù)、小時(shí)數(shù)等不同單位的時(shí)長(zhǎng)
2.比較多個(gè)"MM-dd"格式的日期(月份-日期)大小
可以使用以下幾種方法
只比較日期:
import java.time.MonthDay;
import java.time.format.DateTimeFormatter;
public class CompareTwoDates {
public static void main(String[] args) {
String date1 = "12-31";
String date2 = "01-01";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");
MonthDay md1 = MonthDay.parse(date1, formatter);
MonthDay md2 = MonthDay.parse(date2, formatter);
int result = md1.compareTo(md2);
if (result < 0) {
System.out.println(date1 + " 早于 " + date2);
} else if (result > 0) {
System.out.println(date1 + " 晚于 " + date2);
} else {
System.out.println(date1 + " 等于 " + date2);
}
}
}比較日期并進(jìn)行排序:
import java.time.MonthDay;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class MonthDayComparison {
public static void main(String[] args) {
List<String> dates = Arrays.asList("12-31", "01-01", "06-15", "03-22");
// 轉(zhuǎn)換為MonthDay對(duì)象并排序
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");
Collections.sort(dates, (a, b) -> {
MonthDay md1 = MonthDay.parse(a, formatter);
MonthDay md2 = MonthDay.parse(b, formatter);
return md1.compareTo(md2);
});
System.out.println("排序后的日期: " + dates);
// 輸出: [01-01, 03-22, 06-15, 12-31]
}
}注意事項(xiàng)
- 跨年問(wèn)題:MM-dd 格式不包含年份信息,比較時(shí)只考慮月日
- 格式一致性:確保所有日期使用相同的格式(如都使用"MM-dd"或"M-d")
- 性能考慮:對(duì)于大量日期,MonthDay 方法比字符串分割更高效
- 錯(cuò)誤處理:實(shí)際應(yīng)用中應(yīng)添加格式驗(yàn)證和異常處理
最佳實(shí)踐推薦
對(duì)于 Java 8 及以上版本,推薦使用 MonthDay 類進(jìn)行比較,因?yàn)椋?/p>
- 代碼更簡(jiǎn)潔
- 內(nèi)置日期有效性檢查
- 提供豐富的日期操作方法
3.匯總多個(gè)"HH:mm"格式的時(shí)間點(diǎn),計(jì)算它們的總時(shí)長(zhǎng)
import java.time.Duration;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
public class StreamTimeSum {
public static void main(String[] args) {
List<String> times = List.of("08:15", "01:30", "00:45");
Duration total = times.stream()
.map(t -> LocalTime.parse(t, DateTimeFormatter.ofPattern("HH:mm")))
.map(t -> Duration.ofHours(t.getHour()).plusMinutes(t.getMinute()))
.reduce(Duration.ZERO, Duration::plus);
System.out.printf("總時(shí)長(zhǎng): %d小時(shí)%d分鐘%n",
total.toHours(),
total.toMinutes() % 60);
// 輸出: 總時(shí)長(zhǎng): 10小時(shí)30分鐘
}
}注意事項(xiàng)
- 格式驗(yàn)證:實(shí)際應(yīng)用中應(yīng)添加格式驗(yàn)證,確保輸入都是有效的"HH:mm"格式
- 負(fù)數(shù)處理:如果業(yè)務(wù)需要處理負(fù)時(shí)間,需要額外邏輯
- 性能考慮:對(duì)于大量時(shí)間點(diǎn),Stream API可能稍慢于傳統(tǒng)循環(huán)
- 時(shí)間溢出:當(dāng)總時(shí)長(zhǎng)超過(guò)24小時(shí),確保顯示邏輯能正確處理
最佳實(shí)踐推薦
對(duì)于現(xiàn)代Java項(xiàng)目,推薦使用方法一(Java 8 Duration類):
- 代碼更簡(jiǎn)潔易讀
- 內(nèi)置時(shí)間計(jì)算功能
- 自動(dòng)處理進(jìn)位和溢出
- 提供豐富的轉(zhuǎn)換和操作方法
4.比較多個(gè)"HH:mm"格式時(shí)間的大小
只比較時(shí)間:
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class TimeComparison {
public static void main(String[] args) {
List<String> times = Arrays.asList("08:15", "13:30", "09:45", "05:00");
// 轉(zhuǎn)換為L(zhǎng)ocalTime對(duì)象并排序
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
Collections.sort(times, (a, b) -> {
LocalTime t1 = LocalTime.parse(a, formatter);
LocalTime t2 = LocalTime.parse(b, formatter);
return t1.compareTo(t2);
});
System.out.println("按時(shí)間排序: " + times);
// 輸出: [05:00, 08:15, 09:45, 13:30]
}
}比較時(shí)間并進(jìn)行排序:
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class CompareTwoTimes {
public static void main(String[] args) {
String time1 = "13:45";
String time2 = "09:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
LocalTime t1 = LocalTime.parse(time1, formatter);
LocalTime t2 = LocalTime.parse(time2, formatter);
int result = t1.compareTo(t2);
if (result < 0) {
System.out.println(time1 + " 早于 " + time2);
} else if (result > 0) {
System.out.println(time1 + " 晚于 " + time2);
} else {
System.out.println(time1 + " 等于 " + time2);
}
}
}找出最早最晚時(shí)間:
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
public class FindMinMaxTime {
public static void main(String[] args) {
List<String> times = Arrays.asList("08:15", "13:30", "09:45", "05:00");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
LocalTime min = LocalTime.MAX;
LocalTime max = LocalTime.MIN;
for (String timeStr : times) {
LocalTime time = LocalTime.parse(timeStr, formatter);
if (time.isBefore(min)) {
min = time;
}
if (time.isAfter(max)) {
max = time;
}
}
System.out.println("最早時(shí)間: " + min.format(formatter));
System.out.println("最晚時(shí)間: " + max.format(formatter));
}
}注意事項(xiàng)
- 格式一致性:確保所有時(shí)間字符串使用相同的格式
- 24小時(shí)制:這些方法都假設(shè)使用24小時(shí)制格式
- 錯(cuò)誤處理:實(shí)際應(yīng)用中應(yīng)添加格式驗(yàn)證和異常處理
- 性能考慮:對(duì)于大量時(shí)間點(diǎn),LocalTime方法比字符串分割更高效
最佳實(shí)踐推薦
對(duì)于 Java 8 及以上版本,推薦使用方法一(使用LocalTime類):
- 代碼更簡(jiǎn)潔易讀
- 內(nèi)置時(shí)間有效性檢查
- 提供豐富的時(shí)間操作方法
到此這篇關(guān)于Java根據(jù)MM-dd和HH:mm格式日期計(jì)算時(shí)長(zhǎng)與大小比較的文章就介紹到這了,更多相關(guān)Java時(shí)長(zhǎng)計(jì)算與比較內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springmvc fastjson 反序列化時(shí)間格式化方法(推薦)
下面小編就為大家?guī)?lái)一篇springmvc fastjson 反序列化時(shí)間格式化方法(推薦)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-04-04
Springboot讀取外部配置文件,項(xiàng)目部署時(shí)配置讀取不到問(wèn)題及解決
這篇文章主要介紹了Springboot讀取外部配置文件,項(xiàng)目部署時(shí)配置讀取不到問(wèn)題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06
JavaWeb簡(jiǎn)單用戶登錄注冊(cè)實(shí)例代碼(有驗(yàn)證碼)
這篇文章主要介紹了JavaWeb簡(jiǎn)單用戶登錄注冊(cè)實(shí)例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02
Mybatis-plus實(shí)現(xiàn)主鍵自增和自動(dòng)注入時(shí)間的示例代碼
這篇文章主要介紹了Mybatis-plus實(shí)現(xiàn)主鍵自增和自動(dòng)注入時(shí)間的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
springboot集成druid,多數(shù)據(jù)源可視化,p6spy問(wèn)題
這篇文章主要介紹了springboot集成druid,多數(shù)據(jù)源可視化,p6spy問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01
Java 網(wǎng)絡(luò)爬蟲(chóng)基礎(chǔ)知識(shí)入門(mén)解析
這篇文章主要介紹了Java 網(wǎng)絡(luò)爬蟲(chóng)基礎(chǔ)知識(shí)入門(mén)解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10
基于java語(yǔ)言實(shí)現(xiàn)快遞系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了基于java語(yǔ)言實(shí)現(xiàn)快遞系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03

