目录结构:
DateUtils.java
package dateStudy;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtils {
private static final String FORMAT_1="yyyy-MM-dd HH:mm:ss";
//私有方法,不能new对象
private DateUtils() {
}
//Date类型转为String
public static String dateToString(Date date, String format){
SimpleDateFormat format1 = new SimpleDateFormat(format);
return format1.format(date);
}
//String转为Date类型
public static Date stringTOdate(String date,String format) throws ParseException {
SimpleDateFormat format1 = new SimpleDateFormat(format);//alt+enter抛出异常
return format1.parse(date);
}
//获取当前系统时间转为字符串类型
public static String getSystemTimeString(){
return dateToString(new Date(),FORMAT_1);
}
}
DateTest.java
package dateStudy;
import java.text.ParseException;
import java.util.Date;
public class DateTest {
public static void main(String[] args) throws ParseException {
//date类型转为String类型
Date date = new Date();
String s = DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss");
System.out.println(s);
//日期字符串转成Date类型
Date date1 = DateUtils.stringTOdate(s, "yyyy-MM-dd HH:mm:ss");
System.out.println(date1);
//获取年份 String类型
Date year = new Date();
String strYear = DateUtils.dateToString(year, "yyyy");
System.out.println(strYear.getClass()+": "+strYear);
//获取时间 String类型
Date time = new Date();
String strTime = DateUtils.dateToString(time, "HH:mm:ss");
System.out.println(strTime.getClass()+": "+strTime);
//获取当前系统时间转为字符串类型
System.out.println("当前系统时间为:"+DateUtils.getSystemTimeString());
}
}
结果: