zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Jmeter中的几个重要测试指标释义
    接口测试考虑
    树Hash学习笔记
    kali linux主题美化
    Kali Linux 终端字体配色
    解决github无法打开
    Python requests数据的content和text的区别
    Python+adb操作移动端自动化测试
    linux后台运行python程序
    洛谷P2791 幼儿园篮球题 另解
  • 原文地址:https://www.cnblogs.com/bridgestone29-08/p/6834619.html
Copyright © 2011-2022 走看看