简体   繁体   中英

how can i insert date interval on mysql

I am having a problem to insert the values on TIME_SIGNED_UP attributes on SIGN Table. The SIGN table should display TIME_SIGNED_UP attributes like this
SIGN TABLE TIME_SIGNED_UP 3 years 2 month 2 years 1 month

I have created the table here 

DROP TABLE IF EXISTS SIGN_UP;
CREATE TABLE SIGN_UP(
S_PIN VARCHAR(4),
F_ID INTEGER(4),
TIME_SIGNED_UP DATE,
....
....);

I insert the values here but I am not sure how do i calculate the date interval in order to produce the values on table. I WANT THIS VALUES TO GROW ALL THE TIME SINCE USER SIGNED_UP 3 YEARS AND 2 MONTH AGO. THIS PARTICULAR VALUE MUST BE 4 YEARS AND 2 MONTH AFTER ONE YEAR.

HERE IS MY CALCULATION. INSERT INTO SIGN_UP VALUES('HELLO',4,('2011-08-00' - NOW()));

YouR help would be appreciated.

您可以在MySQL中使用date_add向日期添加间隔

After the user sign up, you don't need to change that value in the database on a daily bases. you would keep that value to know the true data on when they signed up. Then you can calculate the difference based on today's date (the day when the query/page is requested)

Now to calculate the duration since the user signed up, it can be done in many different ways.

If you want this information calculated using MySQL you can try this

SELECT TIMESTAMPDIFF(YEAR,CURDATE(), TIME_SIGNED_UP) AS years,
TIMESTAMPDIFF(MONTH,CURDATE(), TIME_SIGNED_UP) AS months
FROM SIGN_UP

But if you want to find the results using PHP you can try this (code not tested but should work)

// $row is the data set rom after querying the database
$datetime1 = new DateTime($row['TIME_SIGNED_UP']);
$datetime2 = new DateTime('now');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%y year(s), %m month(s)');

Edited after you comment

try this to insert the values (you can't insert HELLO because you column definition is VARCHAR(4)

INSERT INTO SIGN_UP(S_PIN, F_ID, TIME_SIGNED_UP ) 
VALUES('HELL', 4,  
CAST(DATE_ADD(CURDATE(), INTERVAL (UNIX_TIMESTAMP(CURDATE()) - UNIX_TIMESTAMP('2014-08-01')) SECOND) AS DATE)
)

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