I have a column (lastlogin) that contains the following value = '17th May 2017 09:40:43 AM' ----
php function to create stamp:
date('jS F Y h:i:s A');
How can I do a select query that shows the (lastlogin) in that last 30 minutes from current time?
I'm guessing we have to convert date/time to string and separate the 2?
Any help would be amazing.
UPDATE:
I've tried the following but did not work returned more aless of records in table:
SELECT user_id, ('lastlogin' >= DATE_FORMAT(NOW() - INTERVAL 30 MINUTE,'%D %M %Y %H:%m:%s %p')) as result
FROM login_last
where lastlogin >= DATE_FORMAT(NOW() - INTERVAL 30 MINUTE,'%D %M %Y %H:%m:%s %p')
GROUP BY user_id
TABLE Structure
[id] int(8)
[user_id] int(11)
[lastlogin] varchar(30)
[browser] varchar(300)
You will need to convert your string date to a datetime format for the comparison, then compare the current datetime to the value stored.
You could also convert them to sortable strings for comparison. Something like "2017-05-17 10:20:10 AM", but it's easier to compare using the datetime type.
Reference:
str_to_date
date_format
MySQL Query:
SELECT
`user_id`,
`last_login`,
(STR_TO_DATE(`lastlogin`,'%D %b %Y %h:%i:%s %p') >= (NOW() - (INTERVAL 30 MINUTE))) as `in_range`
FROM `login_last`
WHERE (STR_TO_DATE(`lastlogin`,'%D %b %Y %h:%i:%s %p') >= (NOW() - (INTERVAL 30 MINUTE)))
SELECT * FROM tablename WHERE lastlogin >= DATE_SUB(NOW(), INTERVAL 30 MINUTE);
The challenge is to convert the result of DATE_SUB(NOW(), INTERVAL 30 MINUTE) to the correct format '17th May 2017 09:40:43 AM' (or format the left condition alias your lastLogin to UNIX_TIMESTAMP / datetime). In case you are inserting the date values yourself you probably already know how to get that format and can complete that yourself. Otherwise I recommend you to create a new question which is about formatting UNIX_TIMESTAMPs to your desired format.
A blind guess without having the chance to try that on my on would be:
SELECT * FROM tablename
WHERE UNIX_TIMESTAMP(lastlogin) >= DATE_SUB(NOW(), INTERVAL 30 MINUTE);
Related
I am struggling to get the correct definition of "today" and "yesterday" while using CONVERT_TZ() in MySql. My dates are stored in UTC, and I need to query the dates coming out in MST timezone, so something like this produces the correct start time of the day:
select DATE_FORMAT(convert_tz(utc_timestamp(),'+00:00','-07:00'), '%m/%d/%Y 00:00:00')
However, when I put it into a query, it doesn't seem to work.
This query correctly produces the last 24 hours, but not "today" (i.e. the time from midnight to now).
SELECT * FROM tablename
WHERE CONVERT_TZ(insertdate,'+00:00','-07:00') >= convert_tz(DATE_SUB(utc_timestamp(), INTERVAL 1 DAY),'+00:00','-07:00')
Then in similar form, this produces a query that is the 24 hours before 24 hours ago, but isn't "yesterday" (i.e. yesterday from 00:00:00 to 23:59:59 of yesterday's date in MST timezone).
select * from tablename
AND CONVERT_TZ(insertdate,'+00:00','-07:00') >= convert_tz(DATE_SUB(utc_timestamp(), INTERVAL 2 DAY),'+00:00','-07:00')
AND CONVERT_TZ(insertdate,'+00:00','-07:00') <= convert_tz(DATE_SUB(utc_timestamp(), INTERVAL 1 DAY),'+00:00','-07:00')
You need to format your date using date_format function and set the time as "00:00:00" query for today is
SELECT * FROM tablename
WHERE CONVERT_TZ(insertdate,'+00:00','-07:00') >= date_format(convert_tz(utc_timestamp(),'+00:00','-07:00'), '%y-%m-%d 00:00:00');
Yesterday:
SELECT * FROM tablename
WHERE CONVERT_TZ(insertdate,'+00:00','-07:00') between date_format(convert_tz(date_sub(utc_timestamp(), interval 1 day),'+00:00','-07:00'), '%y-%m-%d 00:00:00') and date_format(convert_tz(date_sub(utc_timestamp(), interval 1 day),'+00:00','-07:00'), '%y-%m-%d 23:59:59');
I want to fetch all the products which are near to "expire".
Date format on expiry date column exDate is (Y-m) or YYYY-MM, for example: 2018-03.
I am trying with this query but it fetches all record from the table.
SELECT * FROM product WHERE (exDate BETWEEN DATE_FORMAT(NOW() ,'Y-m') AND NOW()+ interval 2 month)
Turn exDate from the YYYY-MM format into the mySql date format YYYY-MM-DD then perform the query on that value:
SELECT * FROM product WHERE STR_TO_DATE( `exDate`, "%Y-%m" ) BETWEEN CURDATE() AND DATE_ADD( CURDATE(), INTERVAL 2 MONTH)
Take exDate and turn into mySql date format YYYY-MM-DD with
STR_TO_DATE( `exDate`, "%Y-%m" )
Note the % symbol is needed to specify the format.
Then this is the value that must fall into the interval.
Note you can just use CURDATE() to get the current date into date format.
To add a time interval to a date you have to use the mySql function DATE_ADD()
Note that as of today 2018-03-17 you will catch products with exDate with values 2018-04 and 2018-05.
2018-03 is not part of the results as it's turned into 2018-03-01 and is before today (the lower limit).
2018-05 is part of the results because it's turned into 2018-05-01 and is before the upper limit DATE_ADD( CURDATE(), INTERVAL 2 MONTH) that evaluates to 2018-05-17
I'm trying to select a date field which is not in a standard format and only select dates that are older than X number of days. Done some searching and found some examples here but I can't seem to get mine to work.
My date format is like this: Wed Dec 3 09:00:46 2014
which is located in a column: rundate (TEXT)
SELECT * FROM myTable WHERE rundate < DATEADD((day, -5, GETDATE()), '%a %b %e %T %Y')
I get error like: FUNCTION myDB.DATEADD does not exist
Any idea how I can get this to work? My end goal is to delete old records but for now selecting them would be great! Hope you can help.
Cheers
The function you're looking for is date_add (note the underscore).
Moreover, instead of comparing text representations of dates (i.e., converting both to strings), you should be converting the string to a date:
SELECT *
FROM myTable
WHERE STR_TO_DATE(rundate, '%a %b %e %T %Y') <
DATE_ADD(CURDATE(), INTERVAL -5 DAY)
Also, if you want to subtract dates, then date_sub may be a tad more intuitive:
SELECT *
FROM myTable
WHERE STR_TO_DATE(rundate, '%a %b %e %T %Y') <
DATE_SUB(CURDATE(), INTERVAL 5 DAY)
I am using an INSERT ... SELECT query in my MySQL. Now, in my database is a column named "medDate" which I use for my medicine Inventories app. This has a type Varchar and is formatted in this way, "July 2014". Now I want to use the insert...select query to copy the previous month's records. But as I test my query to MySQL, there's an error which says incorrect datetime value. Can you help me with this? This is my query.
INSERT INTO medicinesinventory (itemName, compCode, classID,
medDate, price, beginningIn, newIn,
outMed, sales) SELECT DISTINCT(itemName),
compCode, classID, CURDATE(),
price, 0.0, 0, 0.0, 0.0
FROM medicinesinventory
WHERE YEAR(medDate) = DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%M %Y')
AND MONTH(medDate) = DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%M %Y');
SAMPLE DATA
compCode medID classID medDate itemname price beginningIn newIn outMed sales
GOLDEN 148 20 July 2014 sample 0.00 0 0.00 0.00 6.00
The functions year() and month() require dates. You can get the dates using str_to_date() because MySQL supports "partial" dates (i.e. those without days. So, try this:
WHERE YEAR(str_to_date(meddate, '%M %Y')) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND
MONTH(str_to_date(meddate, '%M %Y')) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
Alternatively, you seem to want to format the previous month in the same format and do the comparison. That can also work:
WHERE medDate = DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%M %Y')
The YEAR() and MONTH() functions operate on expressions of datatype DATE, DATETIME and TIMESTAMP.
If those functions are used on a VARCHAR expression, I believe MySQL will perform an implicit conversion of the VARCHAR to DATE (or DATETIME), expecting format to be 'YYYY-MM-DD' (or 'YYYY-MM-DD %h:%i:%s')
I believe that's where the "incorrect datetime value" error is being thrown.
Just use an expression that generates the VARCHAR value you want to match 'July 2014', and compare the VARCHAR values:
WHERE medDate = DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%M %Y')
As medDate is a string and not a DATETIME you can't use YEAR on this column, but you could convert the right side with DATE_FORMAT and to be consistent you should store the values in the same format.
INSERT INTO medicinesinventory (itemName, compCode, classID,
medDate, price, beginningIn, newIn,
outMed, sales) SELECT DISTINCT(itemName),
compCode, classID,
DATE_FORMAT(CURDATE(), '%M %Y'), -- formatted this date
price, 0.0, 0, 0.0, 0.0
FROM medicinesinventory
-- and converted those in the where clause
WHERE medDate = DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%M %Y')
Note
It would be better, if you could change the data type of the medDate column to DATE.
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.