1 .从String转换为Date参数String类型的格式必须与注释中的日期格式匹配。 如果不匹配,将报告错误。
公共数据传输数据格式(流)数据格式=newsimpledateformat (' yyyy-mm-DD ' ); //日期格式日期=null; try{date=format.parse(time ); }catch(parseexceptione ) { e.printStackTrace ); }返回日期; } system.out.println (string todate (2017-3-16 ) ); //打印测试
顺便说一下,使用datedate=newdate(2017-03-16 ) )。 这种方式直接转换,在高本版的JDk中已经废除,提示这种方法已经过时,并报告错误。
2 .将2.Date转换为String现在转换的String格式与日期格式相匹配。
publicstaticstringdatetostring (datedate ) simpledateformatsformat=newsimpledateformat (' yyy-mm-DD ' ); //日期格式stringtiem=sformat.format(date ); 返回时间; }系统. out.println (date tostring (new date ) ); //打印测试
3 .使用数据库类将字符串转换为Date不会改变格式。 字符串类型为Date类型。 此类的源代码仅支持-作为分隔符,因此必须使用-作为分隔符。
如果将-指定为分隔符,则此方法相对简单。
datedate=Java.SQL.date.value of (2017-3-16 ); 系统. out.println (date;