Date类
Date类:
当我们正常使用Date类时,
Date date = new Date();
System.out.println(date);// Tue Jul 06 11:25:25 CST 2021
不满足我们想要的格式,这个时候我们就需要对日期进行转换,转换成我们需要的格式。
方式一(不推荐使用):
早期的日历类:Calendar
Calendar c1 = Calendar.getInstance();
Calendar c2 = new GregorianCalendar();
int year = c1.get(Calendar.YEAR);
int month = c1.get(Calendar.MONTH);
int day = c1.get(Calendar.DATE);
int hour = c1.get(Calendar.HOUR);
int minute = c1.get(Calendar.MINUTE);
int second = c1.get(Calendar.SECOND);
int millisecond = c1.get(Calendar.MILLISECOND);
StringBuilder builder = new StringBuilder(50);
builder.append(year).append("年").append(month).append("月").append(day).append("日").append(hour).append("时").append(minute).append("分").append(second).append("秒").append(millisecond).append("毫秒");
System.out.println(builder);//2021年6月6日11时25分25秒932毫秒
我们需要分别获取,并拼接字符串进行打印,较为复杂。
方式二:(推荐使用)
// 设置我们想要的日期格式
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss S");
String newDate = dateFormat.format(new Date());
System.out.println(newDate);//2021-07-06 11:25:25 932