Java工具類庫大總結
1. Java自帶工具方法
1.1 List集合拼接成以逗號分隔的字符串
// 如何把list集合拼接成以逗號分隔的字符串 a,b,c
List<String> list = Arrays.asList("a", "b", "c");
// 第一種方法,可以用stream流
String join = list.stream().collect(Collectors.joining(","));
System.out.println(join); // 輸出 a,b,c
// 第二種方法,其實String也有join方法可以實現這個功能
String join = String.join(",", list);
System.out.println(join);
// 輸出 a,b,c
1.2 比較兩個字符串是否相等,忽略大小寫
/* *當我們用equals比較兩個對象是否相等的時候,還需要對左邊的對象進行判空,不然可能會報空指針異常, *我們可以用java.util包下Objects封裝好的比較是否相等的方法 */ System.out.println(Objects.equals(strA, strB)); // 輸出結果:false
1.3 比較兩個對象是否相等
//當我們用equals比較兩個對象是否相等的時候,還需要對左邊的對象進行判空,不然可能會報空指針異常,我們可以用java.util包下Objects封裝好的比較是否相等的方法 String strA = "songwp"; String strB = "SONGWP"; if (strA.equalsIgnoreCase(strB)) { System.out.println("相等"); } // 輸出結果:相等
// 源碼是這樣的 public static boolean equals(Object a, Object b) { return (a == b) || (a != null && a.equals(b)); }
1.4 兩個List集合取交集
List<String> list1 = new ArrayList<>();
list1.add("a");
list1.add("b");
list1.add("c");
List<String> list2 = new ArrayList<>();
list2.add("a");
list2.add("b");
list2.add("d");
list1.retainAll(list2);
System.out.println(list1);
// 輸出結果:[a, b]
2. apache commons工具類庫
apache commons是最強大的,也是使用最廣泛的工具類庫,里面的子庫非常多,下面介紹幾個最常用的
2.1 commons-lang,java.lang的增強版
建議使用commons-lang3,優化了一些api,原來的commons-lang已停止更新
Maven依賴是:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
2.1.1 字符串判空
傳參CharSequence類型是String、StringBuilder、StringBuffer的父類,都可以直接下面方法判空,以下是源碼:
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
public static boolean isNotEmpty(final CharSequence cs) {
return !isEmpty(cs);
}
// 判空的時候,會去除字符串中的空白字符,比如空格、換行、制表符
public static boolean isBlank(final CharSequence cs) {
final int strLen = length(cs);
if (strLen == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
public static boolean isNotBlank(final CharSequence cs) {
return !isBlank(cs);
}
2.1.2 首字母轉成大寫
String str = "yideng"; String capitalize = StringUtils.capitalize(str); System.out.println(capitalize); // 輸出Yideng
2.1.3 重復拼接字符串
String str = StringUtils.repeat("ab", 2);
System.out.println(str); // 輸出abab
2.1.4 格式化日期
// Date類型轉String類型 String date = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"); System.out.println("Date類型轉String類型:"+date); // 輸出結果: Date類型轉String類型:2023-06-06 15:16:13 // String類型轉Date類型 Date date1 = DateUtils.parseDate("2021-05-01 01:01:01", "yyyy-MM-dd HH:mm:ss"); System.out.println("String類型轉Date類型:"+date1); // 輸出結果:String類型轉Date類型:Sat May 01 01:01:01 CST 2021 System.out.println("計算一年后的日期:"+DateUtils.addYears(new Date(), 1)); //輸出結果:計算一年后的日期:Thu Jun 06 15:16:13 CST 2024 System.out.println("計算一個月后的日期:"+DateUtils.addMonths(new Date(), 1)); //輸出結果:輸出結果:計算一個月后的日期:Thu Jul 06 15:16:13 CST 2023 System.out.println("計算一天后的日期:"+DateUtils.addDays(new Date(), 1)); //輸出結果:計算一天后的日期:Wed Jun 07 15:16:13 CST 2023 System.out.println("計算一周后的日期:"+DateUtils.addWeeks(new Date(), 1)); //輸出結果:計算一周后的日期:Tue Jun 13 15:16:13 CST 2023 System.out.println("計算一個小時后的日期:"+DateUtils.addHours(new Date(), 1)); //輸出結果:計算一個小時后的日期:Tue Jun 06 16:16:13 CST 2023 System.out.println("計算一秒后的日期:"+DateUtils.addSeconds(new Date(), 1)); //輸出結果:計算一秒后的日期:Tue Jun 06 15:16:14 CST 2023 System.out.println("計算一分鐘后的日期:"+DateUtils.addMinutes(new Date(), 1)); //輸出結果:計算一分鐘后的日期:Tue Jun 06 15:17:13 CST 2023 System.out.println("計算一毫秒后的日期:"+DateUtils.addMilliseconds(new Date(), 1)); //輸出結果:計算一毫秒后的日期:Tue Jun 06 15:16:13 CST 2023
2.1.5 包裝臨時對象
當一個方法需要返回兩個及以上字段時,我們一般會封裝成一個臨時對象返回,現在有了Pair和Triple就不需要了 // 返回兩個字段 ImmutablePair<Integer, String> pair = ImmutablePair.of(1, "yideng"); System.out.println(pair.getLeft() + "," + pair.getRight());
// 輸出 1,yideng // 返回三個字段 ImmutableTriple<Integer, String, Date> triple = ImmutableTriple.of(1, "yideng", new Date()); System.out.println(triple.getLeft() + "," + triple.getMiddle() + "," + triple.getRight());
// 輸出 1,yideng,Wed Apr 07 23:30:00 CST 2021
2.2 commons-collections 集合工具類
Maven依賴是:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
2.2.1 集合判空
封裝了集合判空的方法,以下是源碼: public static boolean isEmpty(final Collection<?> coll) { return coll == null || coll.isEmpty(); } public static boolean isNotEmpty(final Collection<?> coll) { return !isEmpty(coll); } // 兩個集合取交集 Collection<String> collection = CollectionUtils.retainAll(listA, listB); // 兩個集合取并集 Collection<String> collection = CollectionUtils.union(listA, listB); // 兩個集合取差集 Collection<String> collection = CollectionUtils.subtract(listA, listB);
2.3 common-beanutils 操作對象
Maven依賴: <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.9.4</version> </dependency> public class User { private Integer id; private String name; } 設置對象屬性 User user = new User(); BeanUtils.setProperty(user, "id", 1); BeanUtils.setProperty(user, "name", "yideng"); System.out.println(BeanUtils.getProperty(user, "name")); // 輸出 yideng System.out.println(user); // 輸出 {"id":1,"name":"yideng"} 對象和map互轉 // 對象轉map Map<String, String> map = BeanUtils.describe(user); System.out.println(map); // 輸出 {"id":"1","name":"yideng"} // map轉對象 User newUser = new User(); BeanUtils.populate(newUser, map); System.out.println(newUser); // 輸出 {"id":1,"name":"yideng"}
2.4 commons-io 文件流處理
Maven依賴: <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.8.0</version> </dependency> 文件處理 File file = new File("demo1.txt"); // 讀取文件 List<String> lines = FileUtils.readLines(file, Charset.defaultCharset()); // 寫入文件 FileUtils.writeLines(new File("demo2.txt"), lines); // 復制文件 FileUtils.copyFile(srcFile, destFile);
3. Google Guava 工具類庫
Maven依賴:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>30.1.1-jre</version>
</dependency>
3.1 創建集合
List<String> list = Lists.newArrayList(); List<Integer> list = Lists.newArrayList(1, 2, 3); // 反轉list List<Integer> reverse = Lists.reverse(list); System.out.println(reverse); // 輸出 [3, 2, 1] // list集合元素太多,可以分成若干個集合,每個集合10個元素 List<List<Integer>> partition = Lists.partition(list, 10); // 創建map和set Map<String, String> map = Maps.newHashMap(); Set<String> set = Sets.newHashSet();
3.2 黑科技集合
3.2.1 Multimap 一個key可以映射多個value的HashMap
Multimap<String, Integer> map = ArrayListMultimap.create(); map.put("key", 1); map.put("key", 2); Collection<Integer> values = map.get("key"); System.out.println(map); // 輸出 {"key":[1,2]} // 還能返回你以前使用的臃腫的Map Map<String, Collection<Integer>> collectionMap = map.asMap(); 多省事,多簡潔,省得你再創建 Map<String, List>
3.2.1 BiMap 一種連value也不能重復的HashMap
BiMap<String, String> biMap = HashBiMap.create(); // 如果value重復,put方法會拋異常,除非用forcePut方法 biMap.put("key","value"); System.out.println(biMap); // 輸出 {"key":"value"} // 既然value不能重復,何不實現個翻轉key/value的方法,已經有了 BiMap<String, String> inverse = biMap.inverse(); System.out.println(inverse); // 輸出 {"value":"key"} 這其實是雙向映射,在某些場景還是很實用的。
3.2.3 Table 一種有兩個key的HashMap
// 一批用戶,同時按年齡和性別分組 Table<Integer, String, String> table = HashBasedTable.create(); table.put(18, "男", "yideng"); table.put(18, "女", "Lily"); System.out.println(table.get(18, "男")); // 輸出 yideng // 這其實是一個二維的Map,可以查看行數據 Map<String, String> row = table.row(18); System.out.println(row); // 輸出 {"男":"yideng","女":"Lily"} // 查看列數據 Map<Integer, String> column = table.column("男"); System.out.println(column); // 輸出 {18:"yideng"}
3.2.4 Multiset 一種用來計數的Set
Multiset<String> multiset = HashMultiset.create(); multiset.add("apple"); multiset.add("apple"); multiset.add("orange"); System.out.println(multiset.count("apple")); // 輸出 2 // 查看去重的元素 Set<String> set = multiset.elementSet(); System.out.println(set); // 輸出 ["orange","apple"] // 還能查看沒有去重的元素 Iterator<String> iterator = multiset.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } // 還能手動設置某個元素出現的次數 multiset.setCount("apple", 5);
4.身份證工具類
提供身份證校驗器,身份證信息獲取方法,身份證號碼脫敏方法
package com.utils; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import java.util.stream.IntStream; /** * 身份證工具類 * @author songwp * @create 2023/06/06 */ public class CardUtil { private static final int[] COEFFICIENT_ARRAY = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};// 身份證校驗碼 private static final String[] IDENTITY_MANTISSA = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};// 身份證號的尾數規則 private static final String IDENTITY_PATTERN = "^[0-9]{17}[0-9Xx]$"; /** * 身份證號碼驗證 * 1、號碼的結構 * 公民身份號碼是特征組合碼,由十七位數字本體碼和一位校驗碼組成。從左至右依次為:六位數字地址碼, * 八位數字出生日期碼,三位數字順序碼和一位數字校驗碼。 * 2、地址碼(前六位數) * 表示編碼對象常住戶口所在縣(市、旗、區)的行政區劃代碼,按GB/T2260的規定執行。 * 3、出生日期碼(第七位至十四位) * 表示編碼對象出生的年、月、日,按GB/T7408的規定執行,年、月、日代碼之間不用分隔符。 * 4、順序碼(第十五位至十七位) * 表示在同一地址碼所標識的區域范圍內,對同年、同月、同日出生的人編定的順序號, * 順序碼的奇數分配給男性,偶數分配給女性。 * 5、校驗碼(第十八位數) * (1)十七位數字本體碼加權求和公式 S = Sum(Ai Wi), i = 0, , 16 ,先對前17位數字的權求和 ; * Ai:表示第i位置上的身份證號碼數字值; Wi:表示第i位置上的加權因子 Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 * (2)計算模 Y = mod(S, 11) * (3)通過模( 0 1 2 3 4 5 6 7 8 9 10)得到對應的校驗碼 Y:1 0 X 9 8 7 6 5 4 3 2 */ public static boolean isLegalPattern(String identity) { if (identity == null || identity.length() != 18 || !identity.matches(IDENTITY_PATTERN)) { return false; } char[] chars = identity.toCharArray(); long sum = IntStream.range(0, 17).map(index -> { char ch = chars[index]; int digit = Character.digit(ch, 10); int coefficient = COEFFICIENT_ARRAY[index]; return digit * coefficient; }).summaryStatistics().getSum(); // 計算出的尾數索引 int mantissaIndex = (int) (sum % 11); String mantissa = IDENTITY_MANTISSA[mantissaIndex]; String lastChar = identity.substring(17); return lastChar.equalsIgnoreCase(mantissa); } /** * 通過身份證號碼獲取 生日,年齡,性別代碼 * @param certificateNo 身份證號碼 * @return Map */ public static Map<String, String> getBirthdayAgeSex(String certificateNo) { String birthday = ""; String age = ""; String sexCode = ""; int year = Calendar.getInstance().get(Calendar.YEAR); char[] number = certificateNo.toCharArray(); boolean flag = true; if (number.length == 15) { for (int x = 0; x < number.length; x++) { if (!flag) return new HashMap<String, String>(); flag = Character.isDigit(number[x]); } } else if (number.length == 18) { for (int x = 0; x < number.length - 1; x++) { if (!flag) return new HashMap<String, String>(); flag = Character.isDigit(number[x]); } } if (flag && certificateNo.length() == 15) { birthday = "19" + certificateNo.substring(6, 8) + "-" + certificateNo.substring(8, 10) + "-" + certificateNo.substring(10, 12); sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 3, certificateNo.length())) % 2 == 0 ? "F" : "M"; age = (year - Integer.parseInt("19" + certificateNo.substring(6, 8))) + ""; } else if (flag && certificateNo.length() == 18) { birthday = certificateNo.substring(6, 10) + "-" + certificateNo.substring(10, 12) + "-" + certificateNo.substring(12, 14); sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 4, certificateNo.length() - 1)) % 2 == 0 ? "F" : "M"; age = (year - Integer.parseInt(certificateNo.substring(6, 10))) + ""; } Map<String, String> map = new HashMap<String, String>(); map.put("birthday", birthday); if(ValidateUtil.isEmpty(age)){ map.put("age", "0"); } else { map.put("age", age); } map.put("sexCode", sexCode); return map; } /** * 隱藏身份證某幾位 * @param idCard * @return String */ public static String hideIdCard(String idCard){ return idCard = idCard.replaceAll("(\\d{10})\\d{6}(\\d{2})","$1******$2"); } }
5.手機號碼工具類
提供手機號碼格式校驗器,手機號碼脫敏方法
package com.utils; import org.apache.commons.lang3.StringUtils; import java.util.regex.Pattern; /** * 手機號碼校驗 * @author songwp * @create 2023/06/06 */ public class PhoneUtil { /** * 中國電信號碼格式驗證 手機段: 133,149,153,173,177,180,181,189,199,1349,1410,1700,1701,1702 **/ private static final String CHINA_TELECOM_PATTERN = "(?:^(?:\\+86)?1(?:33|49|53|7[37]|8[019]|99)\\d{8}$)|(?:^(?:\\+86)?1349\\d{7}$)|(?:^(?:\\+86)?1410\\d{7}$)|(?:^(?:\\+86)?170[0-2]\\d{7}$)"; /** * 中國聯通號碼格式驗證 手機段:130,131,132,145,146,155,156,166,171,175,176,185,186,1704,1707,1708,1709 **/ private static final String CHINA_UNICOM_PATTERN = "(?:^(?:\\+86)?1(?:3[0-2]|4[56]|5[56]|66|7[156]|8[56])\\d{8}$)|(?:^(?:\\+86)?170[47-9]\\d{7}$)"; /** * 中國移動號碼格式驗證 * 手機段:134,135,136,137,138,139,147,148,150,151,152,157,158,159,178,182,183,184,187,188,198,1440,1703,1705,1706 **/ private static final String CHINA_MOBILE_PATTERN = "(?:^(?:\\+86)?1(?:3[4-9]|4[78]|5[0-27-9]|78|8[2-478]|98)\\d{8}$)|(?:^(?:\\+86)?1440\\d{7}$)|(?:^(?:\\+86)?170[356]\\d{7}$)"; /** * 中國大陸手機號碼校驗 * @param phone * @return */ public static boolean checkPhone(String phone) { if (StringUtils.isNotBlank(phone)) { if (checkChinaMobile(phone) || checkChinaUnicom(phone) || checkChinaTelecom(phone)) { return true; } } return false; } /** * 中國移動手機號碼校驗 * @param phone * @return */ public static boolean checkChinaMobile(String phone) { if (StringUtils.isNotBlank(phone)) { Pattern regexp = Pattern.compile(CHINA_MOBILE_PATTERN); if (regexp.matcher(phone).matches()) { return true; } } return false; } /** * 中國聯通手機號碼校驗 * @param phone * @return */ public static boolean checkChinaUnicom(String phone) { if (StringUtils.isNotBlank(phone)) { Pattern regexp = Pattern.compile(CHINA_UNICOM_PATTERN); if (regexp.matcher(phone).matches()) { return true; } } return false; } /** * 中國電信手機號碼校驗 * @param phone * @return */ public static boolean checkChinaTelecom(String phone) { if (StringUtils.isNotBlank(phone)) { Pattern regexp = Pattern.compile(CHINA_TELECOM_PATTERN); if (regexp.matcher(phone).matches()) { return true; } } return false; } /** * 隱藏手機號中間四位 * @param phone * @return String */ public static String hideMiddleMobile(String phone) { if (StringUtils.isNotBlank(phone)) { phone = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"); } return phone; } /*public static void main(String[] args) { log.debug(checkPhone("15600000001")); log.debug(hideMiddleMobile("15600000001")); }*/ }
6.中文拼音工具類
提供獲取中文所有漢字首字母,中文首漢字首字母等方法
package com.utils; import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; /** * 中文拼音工具類 * @author songwp * @create 2023/06/06 */ public class PinyinUtil { /** * 獲取第一個漢字的首字母 * @param string * @return */ public static String getPinYinFirstChar(String string) { if(ValidateUtil.isEmpty(string)){ return ""; } return getPinYinHeadChar(string).substring(0,1); } /** * 獲取所有漢字首字母 * @param string * @return */ public static String getPinYinHeadChar(String string) { StringBuilder convert = new StringBuilder(); for (int j = 0; j < string.length(); j++) { char word = string.charAt(j); String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word); if (pinyinArray != null) { convert.append(pinyinArray[0].charAt(0)); } else { convert.append(word); } } return convert.toString().toUpperCase().substring(0,1); } /** * 獲取漢字的所有大寫拼音 eg:NANJINGSHI * @param name * @return * @throws BadHanyuPinyinOutputFormatCombination */ public static String getAllUpperCaseChinese(String name) throws BadHanyuPinyinOutputFormatCombination { char[] charArray = name.toCharArray(); StringBuilder pinyin = new StringBuilder(); HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);//設置大寫格式 defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//設置聲調格式 for(char c:charArray){ if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {//匹配中文,非中文轉換會轉換成null String[] pinyinStringArray = PinyinHelper.toHanyuPinyinStringArray(c,defaultFormat); pinyin.append(pinyinStringArray[0]); } else { pinyin.append(c); } } return pinyin.toString(); } /** * 獲取漢字的所有小寫拼音 eg:nanjingshi * @param name * @return * @throws BadHanyuPinyinOutputFormatCombination */ public static String getAllLowerCaseChinese(String name) throws BadHanyuPinyinOutputFormatCombination { char[] charArray = name.toCharArray(); StringBuilder pinyin = new StringBuilder(); HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);//設置大寫格式 defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//設置聲調格式 for(char c:charArray){ if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {//匹配中文,非中文轉換會轉換成null String[] pinyinStringArray = PinyinHelper.toHanyuPinyinStringArray(c,defaultFormat); pinyin.append(pinyinStringArray[0]); } else { pinyin.append(c); } } return pinyin.toString(); } /** * 獲取漢字的所有首字母大寫拼音 eg:NJS * @param name * @return * @throws BadHanyuPinyinOutputFormatCombination */ public static String getUpperCaseChinese(String name) throws BadHanyuPinyinOutputFormatCombination { char[] charArray = name.toCharArray(); StringBuilder pinyin = new StringBuilder(); HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);//設置大小寫格式 defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//設置聲調格式 for(char c:charArray){//匹配中文,非中文轉換會轉換成null if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) { String[] hanyuPinyinStringArray = PinyinHelper.toHanyuPinyinStringArray(c, defaultFormat); if (hanyuPinyinStringArray != null) { pinyin.append(hanyuPinyinStringArray[0].charAt(0)); } } } return pinyin.toString(); } /** * 獲取漢字的所有首字母小寫拼音 eg:njs * @param name * @return * @throws BadHanyuPinyinOutputFormatCombination */ public static String getLowerCaseChinese(String name) throws BadHanyuPinyinOutputFormatCombination { char[] charArray = name.toCharArray(); StringBuilder pinyin = new StringBuilder(); HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);//設置大小寫格式 defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//設置聲調格式 for(char c:charArray){//匹配中文,非中文轉換會轉換成null if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) { String[] hanyuPinyinStringArray = PinyinHelper.toHanyuPinyinStringArray(c, defaultFormat); if (hanyuPinyinStringArray != null) { pinyin.append(hanyuPinyinStringArray[0].charAt(0)); } } } return pinyin.toString(); } }
7.時間工具類
提供時間,字符串轉換.時間間隔計算,最大時間,最小時間等
package com.utils; import com.chang.util.ValidateUtil; import org.apache.commons.lang.time.DateFormatUtils; import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalAdjusters; import java.util.Calendar; import java.util.Date; /** * 時間工具類 * @author songwp * @create 2023/06/06 */ public class DateUtil { public static String YEAR = "yyyy"; public static String YEARMONTH = "yyyy-MM"; public static String YEARMONTHDAY = "yyyy-MM-dd"; public static String YEARMONTHDAYTIMEBRANCH = "yyyy-MM-dd HH:mm"; public static String YEARMONTHDAYTIMEBRANCHSECOND = "yyyy-MM-dd HH:mm:ss"; public static String YEARMONTHDAYTIMEBRANCHSECONDMILLISECOND = "yyyy-MM-dd HH:mm:ss SSS"; private static long differDay = 1000 * 24 * 60 * 60; private static long differHour = 1000 * 60 * 60; private static long differMinute = 1000 * 60; private static long differSecond = 1000; public static String DIFFERTIME = "0分鐘"; /** * 獲取當前時間戳 yyyy-MM-dd HH:mm:ss * @return String */ public static String getCurrentTime(){ return DateFormatUtils.format(new Date(),YEARMONTHDAYTIMEBRANCHSECOND); } /** * 獲取年 * @return String */ public static String getYear(Date date){ return DateFormatUtils.format(date,YEAR); } /** * 獲取年月 * @return String */ public static String getYearMonth(Date date){ return DateFormatUtils.format(date,YEARMONTH); } /** * 獲取年月日 * @return String */ public static String getYearMonthDay(Date date){ return DateFormatUtils.format(date,YEARMONTHDAY); } /** * 獲取年月日 * @return String */ public static String getYearMonthDayForResult(Date date){ return DateFormatUtils.format(date,"yyyy年MM月dd日"); } /** * 獲取年月日時分 * @return String */ public static String getYearMonthDayTimeBranch(Date date){ return DateFormatUtils.format(date,YEARMONTHDAYTIMEBRANCH); } /** * 獲取年月日時分秒 * @return String */ public static String getYearMonthDayTimeBranchSecond(Date date){ return DateFormatUtils.format(date,YEARMONTHDAYTIMEBRANCHSECOND); } /** * 獲取當月日時分秒毫秒 * @return String */ public static String getYearMonthDayTimeBranchSecondMillisecond(Date date){ return DateFormatUtils.format(date,YEARMONTHDAYTIMEBRANCHSECONDMILLISECOND); } /** * 將時間轉換成固定格式字符串 * @param date 時間 * @param pattern 時間格式 * @return String */ public static String getStringByDate(Date date,String pattern) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); LocalDateTime localDateTime = dateToDateTime(date); return formatter.format(localDateTime); } /** * 將字符串轉換成固定格式時間 yyyy-MM-dd * @param string 時間字符串 * @return Date */ public static Date getDateByString(String string) { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate localDate = LocalDate.parse(string, dateTimeFormatter); return localDateToDate(localDate); } /** * 將字符串轉換成固定格式時間 yyyy-MM-dd HH:mm:ss * @param string 時間字符串 * @return Date */ public static Date getDateTimeByString(String string) { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime localDateTime = LocalDateTime.parse(string, dateTimeFormatter); return dateTimeToDate(localDateTime); } /** * 獲取某天最小時間 * @param date 時間 * @return Date */ public static Date getDateMinTime(Date date) { LocalDateTime localDateTime = dateToDateTime(date); localDateTime = localDateTime.with(LocalTime.MIN); return dateTimeToDate(localDateTime); } /** * 獲取某天最大時間 * @param date 時間 * @return Date */ public static Date getDateMaxTime(Date date) { LocalDateTime localDateTime = dateToDateTime(date); localDateTime = localDateTime.with(LocalTime.MAX); return dateTimeToDate(localDateTime); } /** * 獲取日期之后的某一天時間 * @param date 時間 * @param days 天數 * @return Date */ public static Date getAfterDaysDateTime(Date date, int days) { LocalDateTime localDateTime = dateToDateTime(date); localDateTime = localDateTime.plusDays(days); return dateTimeToDate(localDateTime); } /** * 獲取日期之前的某一天時間 * @param date 時間 * @param days 天數 * @return Date */ public static Date getBeforeDaysDateTime(Date date, int days) { LocalDateTime localDateTime = dateToDateTime(date); localDateTime = localDateTime.minusDays(days); return dateTimeToDate(localDateTime); } /** * 獲取日期月份第一天 00:00:00 000 * @param date 時間 * @return Date */ public static Date getFirstDayOfMonth(Date date) { LocalDateTime localDateTime = dateToDateTime(date); localDateTime = localDateTime.with(TemporalAdjusters.firstDayOfMonth()).with(LocalTime.MIN); return dateTimeToDate(localDateTime); } /** * 獲取日期月份最后一天 23:59:59 999 * @param date 時間 * @return Date */ public static Date getLastDayOfMonth(Date date) { LocalDateTime localDateTime = dateToDateTime(date); localDateTime = localDateTime.with(TemporalAdjusters.lastDayOfMonth()).with(LocalTime.MAX); return dateTimeToDate(localDateTime); } /** * 兩個日期相差多少個月 * @param dateBefore 開始時間 * @param dateAfter 結束時間 * @return Long */ public static Long getUntilMonthByTwoDate(Date dateBefore, Date dateAfter) { LocalDate localDate1 = dateToLocalDate(dateBefore); LocalDate localDate2 = dateToLocalDate(dateAfter); return ChronoUnit.MONTHS.between(localDate1, localDate2); } /** * 兩個日期相差多少天 * @param dateBefore 開始時間 * @param dateAfter 結束時間 * @return Long */ public static Long getUntilDayByTwoDate(Date dateBefore, Date dateAfter) { LocalDate localDate1 = dateToLocalDate(dateBefore); LocalDate localDate2 = dateToLocalDate(dateAfter); return ChronoUnit.DAYS.between(localDate1, localDate2); } /** * 兩個日期相差多少小時 * @param dateBefore 開始時間 * @param dateAfter 結束時間 * @return Long */ public static Long getUntilHoursByTwoDate(Date dateBefore, Date dateAfter) { LocalDateTime localDate1 = dateToDateTime(dateBefore); LocalDateTime localDate2 = dateToDateTime(dateAfter); Long second = Duration.between(localDate1, localDate2).get(ChronoUnit.SECONDS); return second / 3600; } /** * 兩個日期相差多少秒 * @param dateBefore 開始時間 * @param dateAfter 結束時間 * @return Long */ public static Long getUntilHoursByTwoSecond(Date dateBefore, Date dateAfter) { LocalDateTime localDate1 = dateToDateTime(dateBefore); LocalDateTime localDate2 = dateToDateTime(dateAfter); return Duration.between(localDate1, localDate2).get(ChronoUnit.SECONDS); } /** * LocalDateTime轉換為Date * @param localDateTime 時間 * @return Date */ public static Date dateTimeToDate(LocalDateTime localDateTime) { return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); } /** * Date轉換為LocalDateTime * @param date 時間 * @return LocalDateTime */ public static LocalDateTime dateToDateTime(Date date) { return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); } /** * Date轉換為LocalDate * @param date 時間 * @return LocalDate */ public static LocalDate dateToLocalDate(Date date) { return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); } /** * LocalDate轉換為Date * @param localDate 時間 * @return Date */ public static Date localDateToDate(LocalDate localDate) { return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); } /** * 獲取增加天數后的日期 * @param date 時間 * @param days 天數 * @return Date */ public static Date getAddDay(Date date,Integer days){ Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DAY_OF_MONTH, days); return calendar.getTime(); } /** * 獲取當前時間 * @return Date */ public static Date getCurDate() { return new Date(); } /** * 獲取兩個時間相差時間 * @param beforeDate 之前的時間 * @param endDate 之后的時間 * @return String */ public static String getStringDateInfoByTwoDate(Date beforeDate,Date endDate) { long diff = endDate.getTime() - beforeDate.getTime();//獲得兩個時間的毫秒時間差異 long day = diff / differDay;//計算差多少天 long hour = diff % differDay / differHour;//計算差多少小時 long min = diff % differDay % differHour / differMinute;//計算差多少分鐘 long second = diff % differDay % differHour % differMinute / differSecond;//計算差多少秒 String string = ""; if(0 != day){ string = string + day + "天"; } if(0 != hour){ string = string + hour + "小時"; } if(0 != min){ string = string + min + "分鐘"; } if(ValidateUtil.isEmpty(string) && second > 0){//差距小于一分鐘,計算秒 string = second + "秒"; } if(ValidateUtil.isEmpty(string)){//沒有差距則為0分鐘 string = DIFFERTIME; } return string; } /** * 獲取給定年月的最大最小日期 * @param string yyyy-MM * @param flag true 最小日期 false 最大日期 * @return String */ public static String getMonthDayOneAndLast(String string,boolean flag){ Integer year = Integer.parseInt(string.split("-")[0]); Integer month = Integer.parseInt(string.split("-")[1]); if(flag){ return DateUtil.getDayByFlagOfMonth(year, month, true); } return DateUtil.getDayByFlagOfMonth(year, month, false); } /** * 獲取給定年月的第一天和最后一天 * @param year 年 * @param month 月 * @param flag true 第一天,false 最后一天 * @return String */ public static String getDayByFlagOfMonth(int year,int month,boolean flag){ Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, year);//設置年份 calendar.set(Calendar.MONTH, month - 1);//設置月份 if(flag){ calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));//設置日歷中月份的天數 } else { calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));//設置日歷中月份的天數 } return getYearMonthDay(calendar.getTime());//格式化日期 } /** * 計算傳入時間是否超時 * @param longDate 傳入時間 * @param intervalTime 規定時間 秒 * @return boolean */ public static boolean isTimeOut(Long longDate,Long intervalTime){ return new Date(System.currentTimeMillis()).getTime() - new Date(longDate).getTime() / 1000 > intervalTime; } }
古今成大事者,不唯有超世之才,必有堅韌不拔之志!

浙公網安備 33010602011771號