微信搜索lxw1234bigdata | 邀请体验:数阅–数据管理、OLAP分析与可视化平台 | 赞助作者:赞助作者

JAVA通用的字符串转日期

编程语言 lxw1234@qq.com 5803℃ 0评论

因为需求,只写了年月日时的自动转换。

 

 

		
	public static Date convertStringToDate(String time) {
		String separator_yM = "";
		String separator_Md = "";
		String separator_dH = "";
		String yyyy = "";
		String MM = "";
		String dd = "";
		String HH = "";
		Pattern pattern = Pattern
				.compile("(\\d{4})([^\\d]?)(\\d{1,2})([^\\d]?)(\\d{1,2})([^\\d]?)(\\d*)$");
		Matcher matcher = pattern.matcher(time);
		if (matcher.find()) {
			System.out.println(matcher.group(0));
			yyyy = matcher.group(1);
			separator_yM = matcher.group(2);
			MM = matcher.group(3);
			separator_Md = matcher.group(4);
			dd = matcher.group(5);
			separator_dH = matcher.group(6);
			HH = matcher.group(7);
			System.out.println(yyyy + separator_yM + MM + separator_Md + dd + separator_dH + HH);
		}
		
		if(yyyy == null || yyyy.equals("") 
				|| MM == null || MM.equals("")
				|| dd == null || dd.equals("")) {
			return null;
		}
		
		String formateStr = "yyyy" + separator_yM + repeat("M", MM.length()) + separator_Md + repeat("d", dd.length()) + separator_dH + repeat("H", HH.length());
		System.out.println("formateStr->" + formateStr);
		
		SimpleDateFormat formate = new SimpleDateFormat(formateStr);
		formate.setLenient(false);
		Date result = null;
		try {
			result = formate.parse(time);
		} catch (ParseException e) {
		}
		return result;
		
	}
	
	public static String repeat(String s,int counts) {
		int len = s.length();
		StringBuilder builder = new StringBuilder(len * counts);
		for(int i=0; i

测试:

		
	public static void main(String[] args) {
		String s = "2014 9/23:7";
		SimpleDateFormat formate = new SimpleDateFormat("yyyy-MM-dd-HH");
		Date d = convertStringToDate(s);
		if(d != null) {
			System.out.println(formate.format(d));
		} else {
			System.out.println(d);
		}
				
	}

-----输出

2014 9/23:7
2014 9/23:7
formateStr->yyyy M/dd:H
2014-09-23-07

-----

String s = "2014-9/23-7";

---输出

2014-09-23-07

String s = "2014-9/23-7";

---输出

2014-09-23-07

String s = "2014-9/31-7";

---输出

null

String s = "2014-9-ss-7";

---输出

null

其他自己去试吧。

如果觉得本博客对您有帮助,请 赞助作者

转载请注明:lxw的大数据田地 » JAVA通用的字符串转日期

喜欢 (0)
分享 (0)
发表我的评论
取消评论
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址