JAVA通用的字符串转日期

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

 

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<counts; i++){ 
		  builder.append(s); 
		}
		return builder.toString();		
	}

 

测试:

 

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

 

其他自己去试吧。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值