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
  • 相关阅读:
    PHP合并数组array_merge函数运算符加号与的区别
    PHP 字符串为空
    50段超实用CSS代码(1)
    WCF 第三章 信道 总结
    WCF 第三章 信道 操作契约和信道形状
    WCF 第三章 信道
    WCF 第三章 信道形状
    WCF 第二章 契约 数据契约版本
    WCF 第二章 契约 消息契约
    WCF 第二章 契约 系列文章
  • 原文地址:https://www.cnblogs.com/bridgestone29-08/p/6834619.html
Copyright © 2011-2022 走看看