时间格式转换
1 将时间转换成指定格式的字符串
// date 时间 format 格式 如 yyyy-MM-dd
public static String dateToString(Date date, String format)
{
if (date == null)
{
return "";
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
String str = sdf.format(date);
return str;
}
校验
1.国内手机校验
public static boolean isValidPhoneNumber(String phoneNumber) {
// 校验手机号码的正则表达式
String regex = "^(\\+?0?86\\-?)?1[3-9]\\d{9}$";
return phoneNumber.matches(regex);
}
2.邮箱校验
public static boolean isValidEmail(String email) {
// 校验邮箱地址的正则表达式
String regex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
return Pattern.matches(regex, email);
}
3.国内身份证校验
public static boolean isValidIdCard(String id) {
// 校验身份证号码的正则表达式
String regex = "\\d{17}[\\d|x]|\\d{15}";
// 校验身份证号码的系数
int[] coefficient = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
// 校验身份证号码的校验码
char[] checkCode = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
// 判断是否符合身份证号码的格式
if (!id.matches(regex)) {
return false;
}
// 对前17位数字进行加权求和计算校验码
int sum = 0;
for (int i = 0; i < 17; i++) {
int digit = id.charAt(i) - '0';
sum += digit * coefficient[i];
}
// 校验身份证号码的校验码
int remainder = sum % 11;
char calculatedCheckCode = checkCode[remainder];
// 比较计算得到的校验码与身份证号码中的校验码
char actualCheckCode = id.charAt(17);
return actualCheckCode == calculatedCheckCode || (actualCheckCode == 'x' && calculatedCheckCode == 'X');
}
4.性别校验
public static boolean isValidSex(String sex) {
// 校验邮箱地址的正则表达式
if(sex != "0" && sex != "1" && sex != "2")
return false;
return true;
}
5.字符串组是否包含字符串 【完全包含,不区分大小写】
public static boolean inStringIgnoreCase(String str, String... strs)
{
if (str != null && strs != null)
{
for (String s : strs)
{
// 区分大小写用equals()
if (str.equalsIgnoreCase(trim(s)))
{
return true;
}
}
}
return false;
}
// 去掉空格
public static String trim(String str)
{
return (str == null ? "" : str.trim());
}
字符串其它应用
1.字符串指定截取
public static String substring(final String str, int start, int end)
{
if (str == null)
{
return "";
}
if (end < 0)
{
end = str.length() + end;
}
if (start < 0)
{
start = str.length() + start;
}
if (end > str.length())
{
end = str.length();
}
if (start > end)
{
return "";
}
if (start < 0)
{
start = 0;
}
if (end < 0)
{
end = 0;
}
return str.substring(start, end);
}