Java sql.date 秒,向SQL Date添加小时,分钟,秒

在Java SQL Date中,当日期存储为00:00:00时,可能会导致用户误解截止时间为当日午夜。解决此问题的方法是在查询时通过增加一天来实现。在MySQL中,可以使用DATE_ADD函数将时间提前一天。在Java中,可以通过Calendar实例获取日期,然后添加一天,使得结束日期精确到午夜。这样可以确保用户理解的截止时间与数据库中记录的时间一致。

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

Good Day!

I have a problem with SQL Dates. I think the main problem is on the perspective of time.

In my program, I have a start and end date, say for example 2014-01-08 and 2014-01-10.

In the datebase, I used datetime so the dates are stored as 2014-01-08 00:00:00 and 2014-01-10 00:00:00 respectively.

If you are a user and today is the end date, you would assume that the deadline is up to midnight. However, that is not the case because the hours, minutes, and seconds are set to 0.

I would like to ask, what is the best way to add the hours, minutes, and seconds so that the end date is up to midnight.

PS. I am using Java Sql Date.

INSERT INTO survey_schedule (start_date, end_date) VALUES (startDate, endDate);

startDate and endDate are java.sql.date types

解决方案

As mentioned that the date stored as 2013-01-10 00:00:00 is to be converted to 2013-01-10 23:59:59.999 and then take that as end date.

MySql

When you query your date time field, you can advance your endtime by one day as follows

DATE_ADD('your_datetime_field', INTERVAL 1 DAY)

OR

Java code

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// rs is ResultSet reference

long dt = rs.getTimestamp("your_datetime_field").getTime();

// pick calendar instance and set time

Calendar calendar = Calendar.getInstance();

calendar.setTimeInMillis(dt);

// this will print `2013-01-10 00:00:00`

System.out.println(sdf.format(calendar.getTime()));

// advance the date by 1 day

calendar.add(Calendar.Date, 1);

// this is print `2013-01-11 00:00:00`

System.out.println(sdf.format(calendar.getTime()));

Now, you can compare with this Calendar object as well.

Hope this helps.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值