您的位置:首页 > 其它

String和Date的相互转化

2015-09-07 11:01 232 查看
一、String转Date

public static Date String2date(String time){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss.SSS");
		Date date = null;
		try {
			date = sdf.parse(time);
		} catch (ParseException e) {
			e.printStackTrace();
		} 
		return date;
	}


其中String time一定要与simpleDateFormate的格式一致,不然会报Unparseable date的异常

二、Date转String

public static String Date2string(Date date){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss.SSS");
		String str = sdf.format(date);
		return str;
	}


三、String格式的时间转化为另一种String格式

public static String Strdate2another(String str){
		SimpleDateFormat oldsdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss.SSS");
		SimpleDateFormat newsdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String newtime = null;
		try {
			Date date = oldsdf.parse(str);
			newtime = newsdf.format(date);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return newtime;
	}
其中传入的str格式要和oldsdf一致,然后输出的String的时间newtime格式是和newsdf一致的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: