看下代码你就知道了,可直接运行
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Stringordate {
public static void main(String args[]){
String s = "20090420";//这是你要转换为date类型的字符串
SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");//设置一个时间转换器
Date d = null;
try {
d = sf.parse(s);//将字符串s通过转换器转换为date类型
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(d);//输出date类型
System.out.println(sf.format(d));//输出date类型d但以转换器表示的形式打印
}
}
public class DateUtil {
public static final String format1 = "yyyy-MM-dd";
public static final String format2 = "yyyy-MM-dd HH:mm:ss";
public static final String format3 = "HH:mm:ss";
public static final String format4 = "yyyy-MM-dd HH";
public static final String format5 = "yyyyMMddHHmmss";
public static final String format6 = "yyyy年MM月dd日";
/**
* 字符串转化成日期
*
* @param date
* @return
*/
public static Date convert(String date) {
Date retValue = null;
SimpleDateFormat sdf = new SimpleDateFormat(format1);
try {
retValue = sdf.parse(date);
} catch (ParseException e) {
log.error("", e);
}
return retValue;
}
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String strDate = "2012-3-1";
Date date=sdf.parse(strDate);
即可。
SimpleDataFormat(“20111212”)