测试结果:
DataUtil工具类
package javasm.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DataUtil {
public static final String PATTERN1 = "yyyy-MM-dd";
public static final String PATTERN2 = "yyyy-MM-dd HH:mm;ss";
private DataUtil() {
}
public static Date stringConvertToData(String dataStr,boolean flag) {
if (dataStr == null || dataStr.isEmpty()) {
throw new NumberFormatException(dataStr + "数据格式不符合");
}
String result;
if(flag){
result = PATTERN1;
}else {
result = PATTERN2;
}
DateFormat dataFormat = new SimpleDateFormat(result);
try {
return dataFormat.parse(dataStr);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static String dataConvertToString(Date date, boolean flag) {
String result;
if(flag){
result = PATTERN1;
}else {
result = PATTERN2;
}
DateFormat dataFormat = new SimpleDateFormat(result);
return dataFormat.format(date);
}
}
User类
package javasm.demo01;
import javasm.util.DataUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Date;
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
public class User {
private Integer age;
private String name;
private Date birthday;
private Date createTime;
private Date updateTime;
@Override
public String toString() {
return "User{" +
"age=" + age +
", name='" + name + '\'' +
", birthday=" + ((birthday==null)?"": DataUtil.dataConvertToString(birthday,true)) +
", createTime=" + ((createTime==null)?"": DataUtil.dataConvertToString(createTime,false)) +
", updateTime=" + ((updateTime==null)?"null": DataUtil.dataConvertToString(updateTime,false)) +
'}';
}
}
DemoUser测试类
package javasm.demo01;标签:java,DataUtil,String,用户注册,--,DataFormat,result,Date,import From: https://www.cnblogs.com/wang1999an/p/16810415.html
import javasm.util.DataUtil;
import java.util.Date;
import java.util.Scanner;
public class DemoUser {
public static void main(String[] args) {
userRegister();
}
private static void userRegister() {
Scanner input = new Scanner(System.in);
System.out.println("请录入年龄:");
int age = input.nextInt();
System.out.println("请录入姓名:");
String name =input.next();
System.out.println("请录入生日:");
String birthday = input.next();
User user = new User();
user.setAge(age);
user.setName(name);
user.setBirthday(DataUtil.stringConvertToData(birthday,true));
user.setCreateTime(new Date());
System.out.println("注册成功:"+user);
}
}