1、转换方法
//String转换为Date
String strDate=”2017-07-19 08:29:00″;
SimpleDateFormat sdf1=new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);
date=sdf1.parse(strDate);
//Date转换为String
SimpleDateFormat sdf2=new SimpleDateFormat(“yyyyMMdd hh:mm:ss”);
String trans=sdf2.format(date);
2、注意事项
SimpleDateFormat类的parse方法参数字符串的格式一定要和new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);构造函数的入参格式相同,不然会报异常
parse方法源码如下:
public Date parse(String source) throws ParseException
{
ParsePosition pos = new ParsePosition(0);
Date result = parse(source, pos);
if (pos.index == 0)
throw new ParseException(“Unparseable date: \”” + source + “\”” ,
pos.errorIndex);
return result;
}
format方法不接受字符串,但是接受Date类型和数字,将字符串先转换了数字再格式化。
String strDate=”2017-07-19 08:29:00″;
SimpleDateFormat sdf1=new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);
try
{
Long lo=sdf1.parse(strDate).getTime();
SimpleDateFormat sdf3=new SimpleDateFormat(“yyyyMMdd hh:mm:ss”);
sdf3.format(lo);
}
catch (ParseException e1)
{
e1.printStackTrace();
}
3、延伸用法:获取当前时间的前一天以及23:59:59的用法
//获取当前时间的前一个月
Calendar s=Calendar.getInstance();
s.add(Calendar.MONTH,-1);
SimpleDateFormat format=new SimpleDateFormat(“yyyyMM”);
String month=format.format(s.getTime());
//获取前一天的开始和结束时间
Date now=new Date();
Calendar c=new GregorianCalendar();
c.setTime(now);
System.out.println(c.getTime());
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
c.add(Calendar.MILLISECOND, -1);
System.out.println(c.getTime());
SimpleDateFormat sdf=new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
String startTime=sdf.format(c.getTime());
System.out.println(“startTime:”+startTime);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
String endTime=sdf.format(c.getTime());
System.out.println(“endTime:”+endTime);