首页 > 代码库 > String类与Date类的转换

String类与Date类的转换

public class DateTest {
  public static void main(String[] args) throws ParseException {
  Date date = new Date();
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
  String date1 = sdf.format(date);//通过SimpleDateFormat把date类型转换为String类型
  System.out.println(date1);

  String date2 = "2016-11-01 13:10:12";
  Date d2 = sdf.parse(date2);//把String转换为date
  System.out.println(d2);

  System.out.println(date.compareTo(d2));//比较两个时间
  }

}

String类与Date类的转换