最近经常需要时间日期转换,就想着把这些都整理一下
1.Date转String
转换成"yyyy-MM-dd HH:mm:ss"
//获取当前时间
Date currentTime = new Date();
System.out.println(currentTime);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
System.out.println(dateString);
输出:
Wed Oct 12 15:43:02 CST 2022 //当前时间
2022-10-12 15:43:02
转换成"yyyyMM"
//获取当前时间
Date currentTime = new Date();
System.out.println(currentTime);
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMM");
String dateString = formatter.format(currentTime);
System.out.println(dateString);
输出:
Wed Oct 12 15:46:19 CST 2022
202210
2.String转Date
// 将date字符串转化为日期
String date = "2022-01-01";
//先转换成date类型
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date dateTime = format.parse(date);
//对date类型进行格式化
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMM");
String dateString = formatter.format(dateTime);
System.out.println(dateString);
输出:
202201
3.获取当前时间
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int date = c.get(Calendar.DATE);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
int second = c.get(Calendar.SECOND);
int millisecond = c.get(Calendar.MILLISECOND);
System.out.println("年:"+year+"月:"+month+"日:"+date+"时:"+hour+"分:"+minute+"秒:"+second+"毫秒:"+millisecond);
输出:年:2022月:9日:12时:16分:2秒:23毫秒:807