在使用SimpleDateFormat之前,我们来了解一下这个类。SimpleDateFormat
is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date → text), parsing (text → date), and normalization.SimpleDateFormat
allows you to start by choosing any user-defined patterns for date-time formatting.
这个类既可以让date转换为text也可以让text转换为date.总之还是蛮强大的。
用法:从date--->text
1 public static String formatDate(Date date,String format){//date是输入的日期对象,formate是格式。例如“yyyy-MM-dd HH-mm-ss” 2 String result=""; 3 SimpleDateFormat sdf=new SimpleDateFormat(format); 4 if(date!=null) result=sdf.format(date); 5 return result; 6 }
从text-->date
1 public static Date formateString(String str,String format)throws Exception{ 2 if(str==""||str==null) return null;//如果为空返回null 3 SimpleDateFormat sdf=new SimpleDateFormat(format); 4 return sdf.parse(str); 5 }