72 lines
2.2 KiB
Java
Raw Normal View History

2025-07-23 14:19:57 +08:00
package com.czlis.interfaceCommon.utils;
import java.io.UnsupportedEncodingException;
2025-07-23 14:19:57 +08:00
import java.util.Date;
import java.util.Map;
public class LisUtil {
/**
* 生日格式为:yyyy-MM-dd
* 根据出生日期计算年龄
* @param birthday
* @return
*/
public static Map<String,String> getAgeFromBirthDay(String birthday){
return AgeUtils.getAgeFromBirthDay(birthday);
2025-07-23 14:19:57 +08:00
}
/**
* 根据年龄获取出生日期
* @param nl
* @return
*/
public static Date getBirthDayFromAge(int nl, String nldw) {
return AgeUtils.getBirthDayFromAge(nl,nldw);
2025-07-23 14:19:57 +08:00
}
/**
* 按GBK编码的字节宽度截取字符串,最多取cutlens个字节(避免截取半个汉字)
* @param str 原始字符串
* @param beginidx 起始位置
* @param cutlens 截取长度
* @return 截取后的字符串
*/
public static String substringByGbkWidth(String str,int beginidx,int cutlens) {
if (str == null || str.isEmpty()) {
return "";
}
int targetWidth = cutlens; // 目标字节宽度
int currentWidth =beginidx; // 当前累计字节宽度
StringBuilder result = new StringBuilder();
for (char c : str.toCharArray()) {
// 计算当前字符在GBK编码下的字节数
int charWidth;
try {
// GBK编码中,汉字占2字节,英文等占1字节
charWidth = String.valueOf(c).getBytes("GBK").length;
} catch (UnsupportedEncodingException e) {
// 理论上GBK是Java默认支持的编码,不会走到这里
throw new RuntimeException("不支持GBK编码", e);
}
// 判断加上当前字符后是否超过目标宽度
if (currentWidth + charWidth > targetWidth) {
break; // 超过则停止,不截取当前字符
}
// 未超过则累加宽度并添加字符
currentWidth += charWidth;
result.append(c);
// 如果刚好达到目标宽度,提前结束
if (currentWidth == targetWidth) {
break;
}
}
return result.toString();
}
2025-07-23 14:19:57 +08:00
}