字符串转换成日期时间格式

 

 

字符串转换成日期时间格式

 

一、简单版

字符串转换为java.util.Date

只能转换固定、已知格式(形如2012-03-29 09:59:59)的字符串成对应的日期

 

 

关键代码:

/**
 * 字符串不能转化成日期数据及其简单的容错处理
 * */
private static Date dateConvert(String dateString)
{
	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	Date date = new Date();
	try
	{
		date = simpleDateFormat.parse(dateString);
	}
	catch (ParseException e)
	{
		try
		{
			date = simpleDateFormat.parse(DateUtil.getNowDateTime());
		}
		catch (ParseException pe)
		{
			pe.printStackTrace();
		}
		System.out.println("字符串数据不能转换成日期数据.");
	}
	return date;
}
 

 

 

 

二、完美版

字符串转换为java.util.Date

支持格式为

yyyy.MM.dd G 'at' hh:mm:ss z 如 '2002-1-1 AD at 22:10:59 PSD'

yy/MM/dd HH:mm:ss 如 '2002/1/1 17:55:00'

yy/MM/dd HH:mm:ss pm 如 '2002/1/1 17:55:00 pm'

yy-MM-dd HH:mm:ss 如 '2002-1-1 17:55:00' 

yy-MM-dd HH:mm:ss am 如 '2002-1-1 17:55:00 am' 

 

 

关键代码:

/**
 * 字符串转换为java.util.Date
* 支持格式为 yyyy.MM.dd G 'at' hh:mm:ss z 如 '2002-1-1 AD at 22:10:59 PSD'
* yy/MM/dd HH:mm:ss 如 '2002/1/1 17:55:00'
* yy/MM/dd HH:mm:ss pm 如 '2002/1/1 17:55:00 pm'
* yy-MM-dd HH:mm:ss 如 '2002-1-1 17:55:00'
* yy-MM-dd HH:mm:ss am 如 '2002-1-1 17:55:00 am'
* * @param time * String 字符串
* @return Date 日期
*/ public static Date stringToDate(String time) { SimpleDateFormat formatter; int tempPos = time.indexOf("AD"); time = time.trim(); formatter = new SimpleDateFormat("yyyy.MM.dd G 'at' hh:mm:ss z"); if (tempPos > -1) { time = time.substring(0, tempPos) + "公元" + time.substring(tempPos + "AD".length());// china formatter = new SimpleDateFormat("yyyy.MM.dd G 'at' hh:mm:ss z"); } tempPos = time.indexOf("-"); if (tempPos > -1 && (time.indexOf(" ") < 0)) { formatter = new SimpleDateFormat("yyyyMMddHHmmssZ"); } else if ((time.indexOf("/") > -1) && (time.indexOf(" ") > -1)) { formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); } else if ((time.indexOf("-") > -1) && (time.indexOf(" ") > -1)) { formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } else if ((time.indexOf("/") > -1) && (time.indexOf("am") > -1) || (time.indexOf("pm") > -1)) { formatter = new SimpleDateFormat("yyyy-MM-dd KK:mm:ss a"); } else if ((time.indexOf("-") > -1) && (time.indexOf("am") > -1) || (time.indexOf("pm") > -1)) { formatter = new SimpleDateFormat("yyyy-MM-dd KK:mm:ss a"); } ParsePosition pos = new ParsePosition(0); java.util.Date ctime = formatter.parse(time, pos); return ctime; }
 

 

你可能感兴趣的:(J2SE)