Java 生日轉年齡(LocalDate)


生日轉化為年齡,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 }
CustomLocalDateSerializer

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM