日期转为指定格式字符串
package org.maoge.common;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatDemo {
public static void main(String[] args) {
Date date=new Date();
System.out.println(date);
SimpleDateFormat sdf1=new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf3=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf4=new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
System.out.println(sdf1.format(date));
System.out.println(sdf2.format(date));
System.out.println(sdf3.format(date));
System.out.println(sdf4.format(date));
}
}
解析字符串为日期
package org.maoge.common;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatDemo {
public static void main(String[] args) {
SimpleDateFormat sdf1=new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate1="20151010";
String strDate2="20171027 10:00:00";
try {
Date date1=sdf1.parse(strDate1);
System.out.println(date1);
Date date2=sdf2.parse(strDate2);
System.out.println(date2);
} catch (ParseException e) {
e.printStackTrace();
}
}
}