SimpleDateFormat和Calendar

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar date = Calendar.getInstance();
// date.set(Calendar.DATE, 1);
// date.add(Calendar.MONTH, 1);
// date.add(Calendar.DATE, -1);
System.out.println(sdf.format(date.getTime()));

Calendar cal = Calendar.getInstance();
System.out.println("年:" + cal.get(Calendar.YEAR));
System.out.println("月:" + (cal.get(Calendar.MONTH) + 1));
System.out.println("日:" + cal.get(Calendar.DAY_OF_MONTH));
System.out.println("时:" + cal.get(Calendar.HOUR_OF_DAY));
System.out.println("分:" + cal.get(Calendar.MINUTE));
System.out.println("秒:" + cal.get(Calendar.SECOND));

private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {
	@Override
	protected DateFormat initialValue() {
		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	}
};

备注

  • 在Calendar中,月份的下标是从0开始的
  • SimpleDateFormat继承自DateFormat,在DateFormat中定义的protected Calendar calendar是造成多线程不安全的原因,其语句calendar.setTime(date)是根源,多线程下资源抢占是起因
  • 可使用Apache commons里的FastDateFormat,但它只对日期进行format, 不对字符串进行解析
  • 使用Joda-Time类库来处理时间相关问题

你可能感兴趣的:(Java技术进阶)