问题
I have date field in mysql in 1988-04-04 format.I need to calculate age in 25/04 months format.I tried this:
SELECT CONCAT(
FLOOR((curdate() - dob) / 31536000),
'y ',
FLOOR(MOD((curdate() - dob) / 31536000 * 12, 12)),
'm'
) `age` from age
It is giving me 0/0 months. I'll be grateful for any help.
回答1:
When you select curdate()
in a numeric context, you get the yyyymmdd
value, such as 20130812
(for today, August 12, 2013). That's not really that useful for date calculations.
By way of example, my birthdate (old fart that I am) would be 19650202
. When you work out the numeric difference between that and today, you get 480610
.
Now, if you divide that by 31536000
(not sure where you got that from), you definitiely get zero, despite the fact I'm a 48-year-old geezer :-)
You would be far better off using datediff()
to work out the number of days difference between two dates and then applying the correct divide and modulo operations to get full-years and months from that, something like (untested but should be a good start):
select
floor (100 * datediff (curdate(), dob) / 36525) as years,
floor (mod (100 * datediff (curdate(), dob), 36525) / 100 / 30) as months
from age
That won't be perfect since the location of leap-years will affect it a little, the actual days per year is 365.2425
over the long term, and we're assuming exactly 30
days per month but it should be accurate to within a couple of days.
If you want a more accurate measure, you need to find or implement some more exact equations for working out the values.
That's probably going to entail using year()
and month()
to extract the relevant fields from both dob
and the current day and subtracting those, adjusting if if the current date comes before the birthday in the current year.
回答2:
Using DATEDIFF as suggested by paxdiablo:
SELECT
FLOOR(DATEDIFF(CURDATE(), dob) / 365.25) AS years,
FLOOR(MOD(DATEDIFF(CURDATE(), dob), 365.25) / (365.25 / 12)) AS months
FROM age
来源:https://stackoverflow.com/questions/18181555/mysql-query-to-get-age-25-04-months-format-where-date-format-is-1988-04-04