生日转化为年龄,LocalDate数据类型
将LocalDate的birth,转化为int类型的age:
/**
* 生日(用于计算年龄)
*/
@JsonSerialize(using = CustomLocalDateSerializer.class)
private LocalDate birth;
/**
* 年龄(计算得出)
*/
private int age;
关键步骤:
age的get()、set()方法
1 /** 2 * 设置 age 3 * @param age the age set 4 */ 5 public void setAge(int age) { 6 if (this.birth != null) { 7 this.age = (int)this.birth.until(LocalDate.now(), ChronoUnit.YEARS); 8 } 9 } 10 11 /** 12 * 获取 age 13 * @return age 14 */ 15 public int getAge() { 16 if (this.birth != null) { 17 this.age = (int)this.birth.until(LocalDate.now(), ChronoUnit.YEARS); 18 } 19 return this.age; 20 }
LocalDate格式转化类:
1 import java.io.IOException; 2 import java.time.LocalDate; 3 import java.time.format.DateTimeFormatter; 4 5 import com.fasterxml.jackson.core.JsonGenerator; 6 import com.fasterxml.jackson.core.JsonProcessingException; 7 import com.fasterxml.jackson.databind.JsonSerializer; 8 import com.fasterxml.jackson.databind.SerializerProvider; 9 10 public class CustomLocalDateSerializer extends JsonSerializer<LocalDate> { 11 12 @Override 13 public void serialize(LocalDate value, JsonGenerator jgen, 14 SerializerProvider provider) throws IOException, 15 JsonProcessingException { 16 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd"); 17 String str = value.format(formatter); 18 jgen.writeString(str); 19 } 20 21 22 }