springboot项目中Timestamp的使用方法

本文分享了在MySQL数据库中使用时间戳的注意事项,包括如何避免使用Date类型直接查询的异常,以及正确的时间戳比较方法。提供了时间转换为字符串的实用函数,并强调了时间戳格式的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

最近在项目中碰到一个坑和大家分享一下,在mysql数据库时间使用时间戳,在实体类中也是用的Timestamp类型,在根据时间查询的时候,不要用Date类型直接查找会报找不到属性的异常
用以下方法就可以:

// 全局变量
 public static final String TIME_FULL_SPRIT = "yyyy-MM-dd HH:mm:ss";
 
/**
     * 时间转换成字符串
     *
     * @param date 日期
     * @param formartStr 格式
     * @retur
 */
 public static String dateToString(Date date, String formartStr) {
        String strDate = null;
        if (date != null && formartStr != null && !"".equals(formartStr)) {
            SimpleDateFormat sdf = new SimpleDateFormat(formartStr);
            strDate = sdf.format(date);
        }
        return strDate;
    }

//  调用日期转字符串方法,时间戳格式也有严格要求,这个不懂的可以自行百度
 String now = dateToString(new Date(), TIME_FULL_SPRIT);
  Timestamp time = Timestamp.valueOf(now );

两个时间戳比较大小

比较两个时间戳,不能直接用大于小于,要用以下方法:

  Timestamp now = Timestamp.valueOf( dateToString(new Date(), TIME_FULL_SPRIT));
   Timestamp endAt= Timestamp.valueOf( dateToString(new Date(), TIME_FULL_SPRIT));
   if (now.getTime() >=endAt.getTime()) {
                      System.out.println("当前时间大于结束时间");
                    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值