Java中Date转换为Datetime、String与Date的相互转换

本转换在项目中经常遇见,现简要地说明:

(1) Date转换为Datetime

Datetime在java数据库中对应的是Timestamp,转换如下:

		//java.util.Date转换为Timestamp
		Date date = new Date();
		Timestamp timestamp = new Timestamp(date.getTime()); //2013-01-14 22:45:36.484


(2) String转换为Date

		//String转换为java.util.Date
		String str = "2013-01-14";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null; //初始化date
		try {
			date = sdf.parse(str); //Mon Jan 14 00:00:00 CST 2013
		} catch (ParseException e) {
			e.printStackTrace();
		}


(3) Date转换为String

		//java.util.Date转换为String
		Date date = new Date();
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String str = format.format(date); //2013-01-14

(4) String转化为java.sql.Date

转换为java.sql.Date目的是要对数据库进行操作

		//String转换为java.sql.Date
		String str = "2013-01-14";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		java.sql.Date sdate = null; //初始化
		try {
			java.util.Date udate = sdf.parse(str);
			sdate = new java.sql.Date(udate.getTime()); //2013-01-14
		} catch (ParseException e) {
			e.printStackTrace();
		}




你可能感兴趣的:(Java编程,Date转换为Datetime,Date转换为String,String转换为Date)