import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/*日期工具类
构造方法私有,成员方法静态
* */
public class DateUtil {
//无参构造方法
private DateUtil() {
}
//定义成员方法
public static String dateToString(Date time, String format) {
//创建SimpleDateformat对象
SimpleDateFormat sdf = new SimpleDateFormat(format);
String s = sdf.format(time);
return s;
}
public static Date stringToDate(String s, String format) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date parse = sdf.parse(s);//会报错需要用alt+enter生成异常
return parse;
}
}
用法:
import java.text.ParseException;
import java.util.Date;
/*日期工具测试类
* */
public class Datedemo {
public static void main(String[] args) throws ParseException {
//创建日期对象
Date d = new Date();
String s = DateUtil.dateToString(d, "YYYY年MM月dd日 HH:mm:ss");
System.out.println(s);
System.out.println("--------------------------------");
String s1 = "2022-03-23 18:14:59";
Date d1 = DateUtil.stringToDate(s1, "yyyy-MM-dd HH:MM:ss");//报错需要alt+enter惭怍
System.out.println(d1);
}
}