DateFormat是一个抽象类用来将时间对象转化为字符串以及字符串转化为时间对象。
一般用SimpleDateFormat类(DateFormat的实现子类)来实现
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDateFormatAndSimpleDateFormat {
/*
DateFormat是一个抽象类用来将时间对象转化为字符串以及字符串转化为时间对象。
一般用SimpleDateFormat类(DateFormat的实现子类)来实现
*/
public static void main(String[] args) throws ParseException {
/*把时间对象按照“格式字符串指定格式”转成相应的字符串*/
DateFormat df1=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
DateFormat df2=new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
DateFormat df3=new SimpleDateFormat("yyyy-MM-dd");
String str1=df1.format(new Date(4000000));
System.out.println(str1);
System.out.println(df2.format(new Date(4000000)));
System.out.println(df3.format(new Date(4000000)));
/*把字符串按照“格式字符串指定的格式”转成相应的时间对象*/
DateFormat dt1=new SimpleDateFormat("yyyy年MM月dd日 hh时mm分ss秒");
Date date=dt1.parse("2020年5月2日 11时37分45秒");
System.out.println(date);
/*测试其他的格式字符*/
DateFormat df=new SimpleDateFormat("D");//今天是今年的第几天
System.out.println(df.format(new Date()));
}
}