经常需要使用常用的日期格式字符串转化为java的date对象。每次写"yyyy-MM-dd"之类的就好烦,为什么不能直接根据字符串本身格式自动转化吗?于是自己写了个方法把常用转化日期格式字符串自动匹配,然后进行转化。

/***
	 * 智能分析字符串格式,然后进行转化为日期对象。
	 * @param source
	 * @return
	 * @throws ParseException
	 */
	public static Date getDate(String source) throws ParseException{
		if(source == null || "".equals(source)){
			return null;
		}
		DateFormat sdf = null;
		if(source.matches("^[1-9][0-9]{3}-[0-1][0-9]-[0-3][0-9]$")){
			sdf = new SimpleDateFormat("yyyy-MM-dd");
		}
		else if(source.matches("^[1-9][0-9]{3}[0-1][0-9][0-3][0-9]$")){
			sdf = new SimpleDateFormat("yyyyMMdd");
		}
		else if(source.matches("^[1-9][0-9]{3}-[0-1][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9]$")){
			sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		}
		else if(source.matches("^[1-9][0-9]{3}-[0-1][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9]\\.[0-9]{3}$")){
			sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		}
		else{
			throw new ParseException("暂不支持该格式的字符串!" + source, 0);
		}
		return sdf.parse(source);
	}

public static void main(String[] args) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		try {
			System.out.println(getDate(""));
			System.out.println(sdf.format(getDate("2022-13-30")));
			System.out.println(sdf.format(getDate("20221330")));
			System.out.println(sdf.format(getDate("2022-13-30 15:05:24")));
			System.out.println(sdf.format(getDate("2022-13-30 15:05:24.856")));
			System.out.println(getDate("20221330 15:05:24.856"));
		} catch (ParseException e) {
			System.err.println(e.getMessage());
		}
	}

测试结果: 

Logo

永洪科技,致力于打造全球领先的数据技术厂商,具备从数据应用方案咨询、BI、AIGC智能分析、数字孪生、数据资产、数据治理、数据实施的端到端大数据价值服务能力。

更多推荐