实体类中Date转时间戳(Long) BeanUtils的正确使用

springframework中的BeanUtils和hutool中的BeanUtil使用的区别

package com.lezu.springboot.test.bean;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import org.springframework.beans.BeanUtils;

import java.util.Date;

/**
 * @author LianJiaYu
 * @date 2022/8/29 16:05
 * Date转Long时间戳
 */
public class Demo1 {
    public static void main(String[] args) {
        Person p = new Person();
        p.setName("张三");
        p.setBirthday(new Date());
        PersonVo vo = new PersonVo();
        //使用org.springframework.beans.BeanUtils进行复制
        BeanUtils.copyProperties(p, vo);
        System.out.println(vo);
        System.out.println(JSON.toJSONString(vo));
        /** 打印结果
         * PersonVo(name=张三, birthday=1661760658638)
         * {"birthday":1661760658638,"name":"张三"}
         */

        //*************************分割线*************************
        //JSON格式时间戳自动转Date
        Person person = JSON.parseObject("{\"birthday\":1661760658638,\"name\":\"张三\"}", Person.class);
        System.out.println(person);
        /**打印结果
         * Person(name=张三, birthday=Mon Aug 29 16:10:58 CST 2022)
         */


        //*************************分割线*************************

        /**     hutool测试版本为5.8.0
         *      <dependency>
         *             <groupId>cn.hutool</groupId>
         *             <artifactId>hutool-all</artifactId>
         *             <version>5.8.0</version>
         *         </dependency>
         */
        //使用hutool的BeanUtil进行复制
        BeanUtil.copyProperties(p, vo);
        System.out.println(vo);
        System.out.println(JSON.toJSONString(vo));
        /** 打印结果
         * PersonVo(name=张三, birthday=null)
         * {"name":"张三"}
         */
    }
}

@Data
class Person {
    private String name;
    private Date birthday;
}

@Data
class PersonVo {
    private String name;
    private Long birthday;

    public void setBirthday(Date birthday) {
        if (birthday != null) {
            this.birthday = birthday.getTime();
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值