java 获取当前时间及类型转换
1.通过Util包中的Date获取
Date date = new Date();
SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
System.out.println(dateFormat.format(date));
2.通过Util包的Calendar 获取
Calendar calendar= Calendar.getInstance();
SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
System.out.println(dateFormat.format(calendar.getTime()));
3.通过Util包的Calendar 获取时间,分别获取年月日时分秒
Calendar cal=Calendar.getInstance();
int y=cal.get(Calendar.YEAR);
int m=cal.get(Calendar.MONTH);
int d=cal.get(Calendar.DATE);
int h=cal.get(Calendar.HOUR_OF_DAY);
int mi=cal.get(Calendar.MINUTE);
int s=cal.get(Calendar.SECOND);
System.out.println("现在时刻是"+y+"年"+m+"月"+d+"日"+h+"时"+mi+"分"+s+"秒");
java中Date与String的相互转换
java中通过SimpleDateFormat的parse和format方法可以实现Date与String的相互转换
1.String转Date
String str1 = "2021-09-24 12:13:14";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date myDate1 = null;
try {
myDate1 = sdf1.parse(str1);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("myDate1: "+myDate1);
2.Date转String
SimpleDateFormat sdf4 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
String strDate4 = sdf4.format(myDate);
System.out.println("strDate4:" + strDate4);