import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateFormatTest {
public static void main(String[] args) {
Date date = new Date();//获取系统当前时间
System.out.println(date);//Thu Jul 18 11:34:28 CST 2019
Calendar calendar = Calendar.getInstance(); //获取当前的系统时间。
System.out.println(calendar.getTime());//Thu Jul 18 13:38:05 CST 2019
System.out.println("年:"+ calendar.get(Calendar.YEAR));
System.out.println(calendar.get(Calendar.MONTH));//月份从0计,一月是0
System.out.println("月:"+ (calendar.get(Calendar.MONTH)+1));
System.out.println("日:"+ calendar.get(Calendar.DATE));
System.out.println("时:"+ calendar.get(Calendar.HOUR_OF_DAY));
System.out.println("分:"+ calendar.get(Calendar.MINUTE));
System.out.println("秒:"+ calendar.get(Calendar.SECOND));
/**
y 年
M 月
d 日
h 时(12小时计算法)
H 时(24小时计算法)
m 分
s 秒
S 毫秒
*/
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(dateFormat.format(date));//2019-07-18 13:48:52
String str = "2019-07-18 13:48:52";
try {
Date strDate = dateFormat.parse(str);//把字符串转为日期,格式必须与SimpleDateFormat格式相同
System.out.println(strDate);//Thu Jul 18 13:48:52 CST 2019
} catch (ParseException e) {
e.printStackTrace();
}
}
}