目录结构:
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类型转为Stringpublic 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());}
}
结果: