简体   繁体   中英

MySQL calculate yyyy-mm-dd to days

我目前有一列显示用户上次访问特定环境的时间,其格式为2015-01-26 15:35:45我需要能够以某种方式计算/转换格式,因此我可以确定用户在过去45天内访问了环境,并使用current_date作为计算日期。

You can use DATE_SUB to subtract 45 days from current date and compare that with values in your field ie

SELECT DATE_SUB(NOW(), INTERVAL 45 DAY)

which gives 2015-08-09 14:41:55 when executed on 2015-09-23 14:41:55 , hence your query becomes

SELECT * FROM table_name
WHERE last_login_dt > DATE_SUB(NOW(), INTERVAL 45 DAY)

OR

You can use DATEDIFF to subtract two dates, this will return the difference in days between the given dates

SELECT DATEDIFF(NOW(), '2015-09-01')

which gives 21 ie 2015-09-01 is 21 days before current date. So your query should look like

SELECT * FROM table_name
WHERE DATEDIFF(NOW(), last_login_dt) >= 45

assuming that name of your field with last login date is last_login_dt , please change as required

You could use str_to_date to convert the string to a date, and then use datediff to find the days between then and NOW() :

SELECT *
FROM   mytable
WHERE  DATEDIFF(CURRENT_DATE, STR_TO_DATE(last_login, '%Y-%m-%d %H-%i-%s')) >= 45

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM