In my website I show some data according to the date it added to the database. It will place a tag "NEW" to the product which added with in last 7 days. The code works perfectly till today. Now it shows wrong values. I am using the below code to get the difference
DATE(stored_date_time) - DATE_SUB(CURDATE(), INTERVAL 7 DAY) AS days
and the output of this code is 77. But today date is 2014-07-01
while echoing the value of DATE(stored_date_time) it gives the output
2014-07-01
and echoing of DATE_SUB(CURDATE(), INTERVAL 7 DAY) gives the output
2014-06-24
I cant find what is wrong with my code. Please help..
Arun,
Since you asked what is wrong with your code.
select date1 - date2 as days;
It is not actually meaningful at all. The values of dates in number format
are just formed as "yyyymmddhhmmss". So it contains the same information
as the string, but instead of using characters, each digit is actually
an integer. That format might be useful for someone, but you can't use
that format to calculate differences.
Basically what i am trying to say is, if the query above is run for say
'2014-07-02' and '2014-06-22' you'll get 80 as result. Which is in fact
20140702-20140622 =80.
So like you have already been adviced on the other post, use the datediff() function.
Instead of subtracting those date, it would be better if you use DATEDIFF, like below:
SELECT DATEDIFF(day,'2008-06-05','2008-08-05') AS DiffDate
which will return 61.. for more info func_datediff
Try with DATEDIFF function.
SELECT DATEDIFF(DATE(stored_date_time),DATE_SUB(CURDATE(), INTERVAL 7 DAY)) AS days
Just encountered similar issue. I was using CAST((1000000 * (moment2 - moment1)) as UNSIGNED), where moment1 and moment2 are DATETIME(6). And it was working perfectly until once I got enormous value for one of thousands values. What is ridiculous, why it was working all the time, and only one pair of values gave invalid result. Now changed request to TIMESTAMPDIFF(MICROSECOND, moment1, moment2), it works OK.
Related
Using MySQL 5.7, it's pretended a conversion from strings representing four-digit year followed by two-digit month with no any other character in the middle.
For example, running the following statement
SELECT str_to_date('202105','%Y%m');
What is returned: 160101 being January 1601 instead of May 2021. The required arguments seem correct considering the function in cause.
I was not able to reproduce your exact result on DBFiddle, but I did see it creates a null instead of the expected date. What you can do is append a '01' to get a better date literal:
SELECT str_to_date(concat('202105', '01'),'%Y%m%d');
See it here:
https://www.db-fiddle.com/f/sbArVsLF6BVDGSrYdy8geP/0
You need to specify the day as well, otherwise it won't work in MySQL 8.0+.
You need all parts of the date i.e. year, month and day must be specified for the function to operate properly.
# Incorrect Code:
SELECT str_to_date('202105','%Y%m');
# Correct Code:
SELECT str_to_date('20210501','%Y%m%d');
Outputs
2020-05-01
Ref: https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_str-to-date
I need to show current UTC timestamp in a format '2021/05/10T18:30:36Z'
SELECT UTC_TIMESTAMP() FROM XYZ
gives me 2021-05-10 18:30:36
how do i add the / instead of - and use T and Z
select DATE_FORMAT(UTC_TIMESTAMP(),'%Y/%m/%dT%TZ')
2021/05/10T18:51:07Z
Note that T doesn't really mean anything. And Z means UTC ZERO timezone, which is always the case with the UTC_TIMESTAMP function. Thus I have somewhat "hardcoded" those letters at the right place , and they are not real variables accepted by DATE_FORMAT()
I'm trying to display the total travel time that each customer in data time format (00:00:00)
But I'm confused to whether I should just do
SEC_TO_TIME(SUM(endtime - starttime))
or
SEC_TO_TIME(SUM(TIME_TO_SEC(endtime - starttime)))
or
SEC_TO_TIME(SUM(TIME_TO_SEC(endtime) - TIME_TO_SEC(starttime))
if endtime and startime is in datetime format
which one should be the right way to do it. I'm getting a different result for first and the second one
1st:
convert endtime and starttime into timestamp using UNIX_TIMESTAMP
2nd:
subtract them
note: the result will be in seconds
(UNIX_TIMESTAMP(endtime) - UNIX_TIMESTAMP(starttime))
to determine how much time did the costumer consume
3rd:
convert the result into time
SEC_TO_TIME( (UNIX_TIMESTAMP(endtime) - UNIX_TIMESTAMP(starttime)) )
so your final query should be like this
SELECT SEC_TO_TIME( (UNIX_TIMESTAMP(endtime) - UNIX_TIMESTAMP(starttime)) ) FROM travel
Of your three options, I would recommend:
SEC_TO_TIME(SUM(TIME_TO_SEC(endtime)
- TIME_TO_SEC(starttime))
First, I think this is clearest on what you want to do:
Convert the date/times to seconds
Add up the seconds
Convert back to a time
Second, MySQL treats date/time values as numbers in a numeric context. This can produce strange results because 2018-09-13 is turned into 20,180,913, and that is not usually what you want.
As said in the caption I am wondering why the SEC_TO_TIME-Function of MySQL gives me that Zeros at the end.
Refering to the docu (http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_sec-to-time) that shouldn't happen (I am using MySQL 5.0.11).
Any Idea why this Zeros appears and how to get rid of them? To much zeros for displaying miliseconds.
Sine the zeros doens't break MySQLs Date-funcions, it's more a "I don't like that"-Question rather than a real Problem (at least till now^^)
// EDIT: I just figured out that the zeros aren't coming from the SEC_TO_TIME but from the FROM_UNIXTIME()-Function. Thx to #Abhik Chakraborty to ask for the input!
// EDIT2: I used FROM_UNIXTIME(last_try, '%Y-%m-%d %H:%i:%s') to get rid of the zeros. But When I do TIME(FROM_UNIXTIME(last_try, '%Y-%m-%d %H:%i:%s')) the zeros are back. Why??
Seems like every function adds the zeros back. Using SEC_TO_TIME on a simple integer-value also gives zeros...
Here is the whole query iam using:
SELECT
SEC_TO_TIME(FLOOR(TIME_TO_SEC((TIME(FROM_UNIXTIME(`last_try`))))/1800)*1800)
FROM `last48h`
The query reads the timestamp, gets only the time, converts it to seconds, breaks the seconds into half-hours (/1800 gives 0 < x < 48) rounds down and converts back to time
SEC_TO_TIME produces a TIME data type for its result. You can format that as you wish with DATE_FORMAT.
If you actually need subsecond time resolution you'll need to move to version 5.6.4 or beyond.
When you directly SELECT any sort of TIME data type to display, you get a default TIME-to-string conversion operation. The default TIME-to-string conversion in some generations of MySQL yields a string ending in hh:mm:ss+zz00. +zz00 is a timezone indicator, and often displays as +0000. Any chance that's what you're seeing?
It doesn't make sense to try to handle a UNIX_TIMESTAMP() style number of seconds using SEC_TO_TIME(). As of mid-2014 the current unix timestamp value is above 1.39 gigaseconds. TIME data types are used for stuff like elapsed times, and have a limit of just under 839 hours (3 megaseconds, precisely 3020399 seconds), and silently truncate their values.
For example, this is a good use of SEC_TO_TIME:
SELECT SEC_TO_TIME(end_timestamp - start_timestamp) AS duration
edit
Strangely enough, this query
SELECT
SEC_TO_TIME(FLOOR(TIME_TO_SEC((TIME(FROM_UNIXTIME(UNIX_TIMESTAMP()))))/1800)*1800) AS a,
FLOOR(TIME_TO_SEC((TIME(FROM_UNIXTIME(UNIX_TIMESTAMP()))))/1800)*1800 AS b,
TIME_TO_SEC((TIME(FROM_UNIXTIME(UNIX_TIMESTAMP()))))/1800 AS c,
FROM_UNIXTIME(UNIX_TIMESTAMP()) AS d,
FROM_UNIXTIME(UNIX_TIMESTAMP() - UNIX_TIMESTAMP() % 1800) as e
doesn't show any of the 0000 stuff through the phpmyadmin instance I use.
By the way, most people who round time to the nearest interval (a half-hour in your case) prefer to use a modulo and a subtraction; it's less dependent on implicit numerical type conversion than your method.
SELECT TIME(FROM_UNIXTIME(last_try - last_try%1800))
does what the query in your question does.
I had the same problem with the 'SEC_TO_TIME' function.
I had overlooked the fact that I was storing timestamps as a VARCHAR.
I changed my datatypes from VARCHAR to BIGINT and it is formatting the output values as expected (hh:mm:ss).
Try to use TIME_FORMAT with %k specifier it should help.
The main problem is, that I have stored in database datetime , not the date (what I need). Ok never mind.
I have thousands of reports stored each day.
I need to LEFT by 10 my datetime_view (to cut the time) and everything's fine. Except this. I'm trying to figure out why do I have to put in the condition + one day from the future? Otherwise it won't search what I want.
SELECT
LEFT(datetime_view,10),
count(type)
FROM reports
WHERE
type IN (1,2,5)
AND
datetime_view>='2012-10-28'
AND
datetime_view<='2012-11-04'
group by LEFT(datetime_view,10);
You can see I must search from the future. Why??
It gives me an output from 28.10 to 3.11 ....
don't use string operations on date/time values. MySQL has a huge set of functions for date/time manipulation. Try
GROUP BY DATE(datetime_view)
instead, which will extract only the date portion of the datetime field. Your string operation is not y10k compliant. Using the date() function is.
As for your plus one day, consider how the comparisons are done: A plain date value, when used in date/time comparisons, has an implicit 00:00:00 time value attached to it, e.g. all dates have a time of "midnight".
i think it's better to use DATE(datetime_view) to cut the time instead of LEFT(datetime_view,10), also on the where condition:
DATE(datetime_view) <= '2012-11-03'