Android 判断输入的年月日是否合法-正则表达
16lz
2021-01-23
判断输入的年月日是否合法的工具类如下,可直接复制粘贴使用:
package com.company.utils;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.regex.Matcher;import java.util.regex.Pattern;public class ValidDateUtil { private static final String TAG = ValidDateUtil.class.getSimpleName(); public static boolean validDateTime(String timeStr) { String format = "((19|20)[0-9]{2})-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01]) " + "([01]?[0-9]|2[0-3]):[0-5]?[0-9]:[0-5]?[0-9]"; Pattern pattern = Pattern.compile(format); Matcher matcher = pattern.matcher(timeStr); if (matcher.matches()) { pattern = Pattern.compile("(\\d{4})-(\\d+)-(\\d+).*"); matcher = pattern.matcher(timeStr); if (matcher.matches()) { int y = Integer.valueOf(matcher.group(1)); int m = Integer.valueOf(matcher.group(2)); int d = Integer.valueOf(matcher.group(3)); if (d > 28) { Calendar c = Calendar.getInstance(); c.set(y, m - 1, 1); int lastDay = c.getActualMaximum(Calendar.DAY_OF_MONTH); return (lastDay >= d); } } return true; } else { return false; } }}
使用方式如下,因为只判断年月日,因此时分秒我默认都是00,主要是为了套用SimpleDateFormat的格式:
private long refreshAddTime() { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); StringBuilder sb = new StringBuilder(); sb.append(mEditYear.getEditableText().toString()).append("-"); sb.append(mEditMonth.getEditableText().toString()).append("-"); sb.append(mEditDay.getEditableText().toString()).append(" "); sb.append("00").append(":").append("00").append(":").append("00"); Log.d(TAG,"refreshAddTime: contract string: " + sb.toString()); try { Date addTime = format.parse(sb.toString()); //判断加入时间是否大于当前时间 if (System.currentTimeMillis() < addTime.getTime()){ ToastUtil.showCustomToast(mContext,mContext.getResources().getString(R.string.add_time_error)); mAddTimeIsOk = false; return 0; } //判断加入时间是否为有效输入 if (ValidDateUtil.validDateTime(sb.toString())){ Log.d(TAG,"ValidDateUtil: is valid date!!!!"); mAddTimeIsOk = true; return addTime.getTime()/1000; } else { mAddTimeIsOk = false; ToastUtil.showCustomToast(mContext,mContext.getResources().getString(R.string.input_add_time_error)); } } catch (ParseException e) { mAddTimeIsOk = false; ToastUtil.showCustomToast(mContext,mContext.getResources().getString(R.string.input_add_time_error)); FoodLog.e(TAG,"add time error!!!!!"); } return 0; }
更多相关文章
- Android开发中 获取当前Android的年月日时分秒的时间
- android获取系统当前年月日时分秒的时间
- Android日期空间(DatePickerDialog)中的年月日不全部显示
- android 年月日选择器(可选择年,年月,年月日)
- PHP实现根据出生年月日计算年龄的功能(代码示例)
- 如何实现php中date只显示年月日
- php如何计算两个时间戳之间相差的日时分秒
- js获取毫秒值以及转换成年月日时分秒等
- oracle --sql--转换表字段日期格式(年月日时分秒转换年月日)