You辉编程-Java通用工具类(持续更新)
1、传入yyyyMMdd返回yyyy-MM-dd字符串日期(两天前)
public static String resStringDate(String inputDate) {
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyyMMdd");
sourceFormat.setLenient(false);
SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = null;
try {
Date date = sourceFormat.parse(inputDate);
// 使用 Calendar 来操作日期
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, -2); // 减去两天
// 获取减去两天后的日期
Date twoDaysBefore = calendar.getTime();
formattedDate = targetFormat.format(twoDaysBefore);
return formattedDate;
} catch (ParseException e) {
e.printStackTrace();
}
return formattedDate;
}
2、格式化日期为 yyyy年MM月dd日
public static String getYearMonthDdy(String dateStr) {
for (DateTimeFormatter formatter : DATE_FORMATTERS) {
try {
LocalDate date = LocalDate.parse(dateStr, formatter);
return date.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
} catch (DateTimeParseException e) {
// 忽略解析异常,尝试下一个格式
}
}
throw new IllegalArgumentException("无法解析日期: " + dateStr);
}
3、返回List 中 具体字段降序排序后前n名的属性名
/**
* 示例:String zyList = getTopNNames(data, "降序字段", "字段属性", 3, "、");
* @param data
* @param sortFieldName
* @param mapFieldName
* @param limit
* @param delimiter
* @return
* @param <T>
* @throws NoSuchFieldException
* @throws IllegalAccessException
*/
public static <T> String getTopNNames(List<T> data, String sortFieldName, String mapFieldName, int limit, String delimiter) throws NoSuchFieldException, IllegalAccessException {
Field sortField = null;
Field mapField = null;
if (data == null || data.isEmpty()) {
return "";
}
// 获取字段对象
Class<?> clazz = data.get(0).getClass();
sortField = clazz.getDeclaredField(sortFieldName);
mapField = clazz.getDeclaredField(mapFieldName);
// 设置字段可访问
sortField.setAccessible(true);
mapField.setAccessible(true);
Field finalMapField = mapField;
Field finalSortField = sortField;
return data.stream()
.sorted((o1, o2) -> {
try {
BigDecimal value1 = (BigDecimal) finalSortField.get(o1);
BigDecimal value2 = (BigDecimal) finalSortField.get(o2);
return value2.compareTo(value1);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
})
.limit(limit)
.map(item -> {
try {
return (String) finalMapField.get(item);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
})
.collect(Collectors.joining(delimiter));
}
4、获取近6个月的期日(yyyyMMdd)
/**
* 获取近6个月的期日(yyyyMMdd)
* @param dateStr
* @return
*/
public static List<String> getPreviousSixMonths(String dateStr) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
// 将字符串解析为LocalDate
LocalDate date = LocalDate.parse(dateStr, formatter);
// 创建一个列表,用于存放之前六个月的所有日期
List<String> previousSixMonths = new ArrayList<>();
// 将当前日期添加到列表中
previousSixMonths.add(dateStr);
// 循环遍历之前的五个月
for (int i = 1; i <= 5; i++) {
// 计算五个月之前的日期
LocalDate previousMonth = date.minusMonths(i);
// 计算五个月之前的月份的最后一天
LocalDate lastDayOfMonth = LocalDate.of(previousMonth.getYear(), previousMonth.getMonth(), 1)
.withDayOfMonth(previousMonth.getMonth().length(previousMonth.isLeapYear()));
// 将五个月之前的月份的最后一天添加到列表中
previousSixMonths.add(lastDayOfMonth.format(DateTimeFormatter.ofPattern("yyyyMMdd")));
}
// 将列表中的元素反转
Collections.reverse(previousSixMonths);
// 返回之前六个月的日期列表
return previousSixMonths;
}
5、返回该月与上月的同一天
public static String getPreviousMonth(String dateString) {
// 定义日期格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
// 将输入的字符串转换为LocalDate对象
LocalDate date = LocalDate.parse(dateString, formatter);
// 获取上个月的年月
YearMonth previousMonth = YearMonth.from(date).minusMonths(1);
// 尝试获取上个月的同一天
LocalDate result = date.minusMonths(1);
// 如果上个月没有该日期,则返回上个月的最后一天
if (result.getMonth() != previousMonth.getMonth()) {
result = previousMonth.atEndOfMonth();
}
// 将结果格式化为字符串并返回
return result.format(formatter);
}
6、返回指定字段值名次
/**
* @param list
* @param rankByField 需要获取名次的指标
* @param rankFieldName 名次属性
* @return 返回指定字段值名次
* @param <T>
* @throws NoSuchFieldException
* @throws IllegalAccessException
*/
public static <T> List<T> getRankByField(List<T> list, String rankByField, String rankFieldName) throws NoSuchFieldException, IllegalAccessException {
if (rankByField == null || rankByField.isEmpty()) {
throw new IllegalArgumentException("必须提供需要获取名次的字段名称!");
}
if (rankFieldName == null || rankFieldName.isEmpty()) {
throw new IllegalArgumentException("必须提供排名的字段名称!");
}
// 创建一个按rankByField排序的对(索引、值)列表
List<Map.Entry<Integer, Comparable>> indexedList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
Field field = list.get(i).getClass().getDeclaredField(rankByField);
field.setAccessible(true);
Comparable value = (Comparable) field.get(list.get(i));
indexedList.add(new AbstractMap.SimpleEntry<>(i, value));
}
// 按rankByField按降序对列表进行排序
indexedList.sort((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()));
// 分配排名,当值相等时共享名次,次之的rankByField大小紧跟其后
int rank = 1;
int previousRank = 1;
for (int i = 0; i < indexedList.size(); i++) {
if (i > 0 && indexedList.get(i).getValue().compareTo(indexedList.get(i - 1).getValue()) != 0) {
rank = previousRank + 1;
}
int originalIndex = indexedList.get(i).getKey();
T item = list.get(originalIndex);
Field rankField = item.getClass().getDeclaredField(rankFieldName);
rankField.setAccessible(true);
rankField.set(item, rank);
previousRank = rank;
}
return list;
}