How sum 24 hours to time mysql? - mysql

I've got a column time type in mysql, i want to add 24 hours to this hour, i try with code below:
SELECT SUBSTRING(CAST(DATE_ADD(STR_TO_DATE('23:00', '%k:%i'), INTERVAL (TIME_TO_SEC('24:00') / 60) MINUTE) AS CHAR(8)), 1,5)
I need to return 23:00 again (because i add 24 hours but that 23:00 is of the next day) but this code return me 47:00.
Some help?

I think you're looking for ADDTIME
SELECT ADDTIME(‘23:00’,’24:00’)
https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_addtime

You need to first convert the column value to a datetime, add the hours, and then convert the result back to time:
select cast(date_add(cast(time_column as datetime), interval 24 hour ) as time)
from yourtable;
Example:
select cast(date_add(cast(cast('23:00' as time) as datetime), interval 24 hour ) as time)

The TIME type allows you to store up to (but not including) 839 hours (positive and negative). That's great if you need to store duration, but not so much if you want to store time of day. If you want the latter you should consider the DATETIME type instead.

Related

Find all rows where start and end are 14 hours apart

Our table has start_time and end_time as unix epoch timestamps. I'd like to find all the rows where the end_time is exactly 14 hours (50400) greater than the start time.
SELECT * FROM `mrbs_entry` WHERE (`end_time`-`start_time`)==50400
This seems slightly off, and in fact doesn't work. I'm not sure what the proper terminology to search though.
You shouldn't use == for comparing the values, but =.
Or you can use FROM_UNIXTIME to format is as date and then DATESUB with INTERVAL 14 HOUR. So it's:
SELECT * FROM `mrbs_entry`
WHERE DATE_SUB(FROM_UNIXTIME(`end_time`), INTERVAL 14 HOUR) = FROM_UNIXTIME(`start_time`);

Find records with a time field in the last 24 hours

In my SQL query how do i find records in the last 24 hours?
I am using time() function for inserting into db.
I am using time-stamp the time is stored in this format.Eg 1332673046
select somefield from yourtable where timefield >= subtime(current_timestamp(), '1 00:00:00');
You can use BETWEEN
SELECT * FROM users
WHERE created_at BETWEEN '2012-03-31 00:00:00 UTC' AND '2012-03-31 23:59:59 UTC'
I am not certain if you are looking to check within the same calendar day, or as you say within the past 24 hours, so here's what I usually do for both cases:
a) For the same calendar day:
CONVERT(VARCHAR(8), myTable.myDate, 112) = CONVERT(VARCHAR(8), GETDATE(), 112)
b) For the date to be within the past 24 hours (inclusive)
DATEDIFF(hour, myTable.myDate, GETDATE()) <= 24
Simple DATE arithmetic would do,
SELECT *
FROM `table1`
WHERE `time_col` BETWEEN NOW() AND NOW()- INTERVAL 24 HOURS;
Given that you are storing dates as unix timestamps then you need UNIX_TIMESTAMP like this
SELECT
// fields you need
FROM `table`
WHERE
`date_field` BETWEEN UNIX_TIMESTAMP( DATE_SUB(NOW() INTERVAL 24 HOUR) ) AND UNIX_TIMESTAMP()
You might want to consider storing dates in MySQLs DATETIME format as it makes date calculations in MySQL much easier.

MYSQL Date Time Round To Nearest Hour

I have a date time field in a MySQL database and wish to output the result to the nearest hour.
e.g. 2012-04-01 00:00:01 should read 2012-04-01 00:00:00
Update: I think https://stackoverflow.com/a/21330407/480943 is a better answer.
You can do it with some date arithmetic:
SELECT some_columns,
DATE_ADD(
DATE_FORMAT(the_date, "%Y-%m-%d %H:00:00"),
INTERVAL IF(MINUTE(the_date) < 30, 0, 1) HOUR
) AS the_rounded_date
FROM your_table
Explanations:
DATE_FORMAT: DATE_FORMAT(the_date, "%Y-%m-%d %H:00:00") returns the date truncated down to the nearest hour (sets the minute and second parts to zero).
MINUTE: MINUTE(the_date) gets the minute value of the date.
IF: This is a conditional; if the value in parameter 1 is true, then it returns parameter 2, otherwise it returns parameter 3. So IF(MINUTE(the_date) < 30, 0, 1) means "If the minute value is less than 30, return 0, otherwise return 1". This is what we're going to use to round -- it's the number of hours to add back on.
DATE_ADD: This adds the number of hours for the round into the result.
Half of the hour is a 30 minutes. Simply add 30 minutes to timestamp and truncate minutes and seconds.
SELECT DATE_FORMAT(DATE_ADD(timestamp_column, INTERVAL 30 MINUTE),'%Y-%m-%d %H:00:00') FROM table
soul's first solution truncates instead of rounding and the second solution doesn't work with Daylight Savings cases such as:
select FROM_UNIXTIME(UNIX_TIMESTAMP('2012-03-11 2:14:00') - MOD(UNIX_TIMESTAMP('2012-03-11 2:14:00'),300));
Here is an alternate method (1):
DATE_ADD(
tick,
INTERVAL (IF((MINUTE(tick)*60)+SECOND(tick) < 1800, 0, 3600) - (MINUTE(tick)*60)+SECOND(tick)) SECOND
)
If you don't need to worry about seconds you can simplify it like this (2):
DATE_ADD(
tick,
INTERVAL (IF(MINUTE(tick) < 30, 0, 60) - MINUTE(tick)) MINUTE
)
Or if you prefer to truncate instead of round, here is simpler version of soul's method (3):
DATE_SUB(tick, INTERVAL MINUTE(tick)*60+SECOND(tick) SECOND)
EDIT: I profiled some of these queries on my local machine and found that for 100,000 rows the average times were as follows:
soul's UNIXTIME method: 0.0423 ms (fast, but doesn't work with DST)
My method 3: 0.1255 ms
My method 2: 0.1289 ms
Ben Lee's DATE_FORMAT method: 0.1495 ms
My method 1: 0.1506 ms
From How to round a DateTime in MySQL?:
It's a little nasty when you do it with datetime data types; a nice candidate for a stored function.
DATE_SUB(DATE_SUB(time, INTERVAL MOD(MINUTE(time),5) MINUTE ),
INTERVAL SECOND(time) SECOND)
It's easier when you use UNIXTIME timestamps but that's limited to a 1970 - 2038 date range.
FROM_UNIXTIME(UNIX_TIMESTAMP(time) - MOD(UNIX_TIMESTAMP(time),300))
Good luck.
To round down to the current hour, select:
FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(column_name) / 3600) * 3600).
The value is expressed in the current time zone doc
This will return the next hour, that is '2012-01-02 18:02:30' will be converted into '2012-01-02 19:00:00'
TIMESTAMPADD(HOUR,
TIMESTAMPDIFF(HOUR,CURDATE(),timestamp_column_name),
CURDATE())
Instead of CURDATE() you can use an arbitrary date, for example '2000-01-01'
Not sure if there could be problems using CURDATE() if the system date changes between the two calls to the function, don't know if Mysql would call both at the same time.
to get the nearest hour would be:
TIMESTAMPADD(MINUTE,
ROUND(TIMESTAMPDIFF(MINUTE,CURDATE(),timestamp_column_name)/60)*60,
CURDATE())
changing 60 by 15 would get the nearest 15 minutes interval, using SECOND you can get the nearest desired second interval, etc.
To get the previous hour use TRUNCATE() or FLOOR() instead of ROUND().
Hope this helps.
If you need to round just time to next hour you may use this:
SELECT TIME_FORMAT(
ADDTIME(
TIMEDIFF('16:15', '10:00'), '00:59:00'
),
'%H:00:00'
)
I think this is the best way, since it also will use the least amount of resources-
date_add(date(date_completed), interval hour(date_completed) hour) as date_hr

MySQL "day" - how do I get an exact figure?

I am using this function to filter query results that are older than 60 days:
s.timeSubmitted >= ( CURDATE() - INTERVAL 60 DAY )
The problem is, the "60 days" part doesn't seem to be an exact figure. I want it to filter right where s.timeSubmitted is longer than 60 days, down to the exact second of s.timeSubmitted.
How do I write "60 Days" as an exact figure (down to the second)?
The problem is that CURDATE() returns a DATE type, not a DATETIME type (an instant in time). The result of subtracting an interval from a DATE is also a DATE.
Instead, try this:
s.timeSubmitted >= ( NOW() - INTERVAL 60 DAY )
This gives you what you want, because NOW() returns a DATETIME, so the result of the subtraction is also a DATETIME.
INTERVAL 60 DAY is exact - your problem is that CURDATE() isn't. It returns whole days, not the current time.
Use NOW() instead!
I usually do
now()-interval 60 day
Assuming you want the same time of day 60 days ago;
s.timeSubmitted >= ( now() - interval 60 day);
Maybe an un-necessary note in this case; 1 day ago may be 23, 24 or 25 hours ago depending on DST changes, if you want a specific number of hours as an interval, don't use a day instead of 24 hours.

How to Subtract Days in MySQL

How can I subtract time in MySQL? For example, today is 16 March; I want to subtract 15 days to reach 1 March. Are there any methods that can be used to subtract 15 days from the current date?
SELECT DATE(NOW()-INTERVAL 15 DAY)
For a list of units see http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-add
Not entirely related to this question but is related to the title:
SELECT SUBTIME("10:24:21", "5"); -- subtracts 5 seconds. (returns "10:24:16")
SELECT SUBTIME("10:24:21", "01:00:00"); -- subtracts one hour. (returns "09:24:21")
Documentation: MySQL SUBTIME function
Use:
SELECT NOW() - INTERVAL 15 DAY
to keep the datetime precision.
You can use this :
SELECT DATE(NOW()-INTERVAL 15 DAY);
for when you want to subtract the number of days.
In order to subtract the time instead, say 15 minutes, the following should work:
SELECT(DATE_SUB(NOW(), INTERVAL '15:0' MINUTE_SECOND));
Adding the reference link again :- https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-add.
Yes its possible using date function in Mysql
select distinct
lastname,
changedat, date_add(changedat, interval -15 day) as newdate
from employee_audit;
lastname and changedat is field name and employee_audit is table name.
I have subtract 15 days from my date - check image please. thanks