Date date = new Date();
//EEEE是星期, MMMM是月
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateFormat shortDateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT);
DateFormat mediumDateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM);
DateFormat longDateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG);
DateFormat fullDateFormat = DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.FULL);
DateFormat df=DateFormat.getDateInstance();
System.out.println(sdf.format(date));
System.out.println(shortDateFormat.format(date));
System.out.println(mediumDateFormat.format(date));
System.out.println(longDateFormat.format(date));
System.out.println(fullDateFormat.format(date));
System.out.println(df.format(new Date()));
输出结果:
2018-05-17 10:15:28
18-5-17 上午10:15
2018-5-17 10:15:28
2018年5月17日 上午10时15分28秒
2018年5月17日 星期四 上午10时15分28秒 CST
2018-5-17
- 字符串转时间格式
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
String str = "2018-08-09";
try {
System.out.println(fmt.parse(str));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
输出结果:
Thu Aug 09 00:00:00 CST 2018
- 日历类型时间格式(当前时间:2018/5/17)
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL);
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new Date());
cal.set(GregorianCalendar.DAY_OF_WEEK,GregorianCalendar.FRIDAY);
System.out.println(dateFormat.format(cal.getTime()));
输出结果:
2018年5月18日 星期五
- 其他
date.getTime();和System.currentTimeMillis();均为当前计算机时间和GMT时间(格林威治时间)1970年1月1号0时0分0秒所差的毫秒数。
- jsp时间格式化
<fmt:formatDate value="${date }" pattern="E"/> //E为星期