Skip to content

Calculate age based on id #2

Description

@tgranqvist

Add a user defined function to calculate the current age based on the id code.

CREATE OR REPLACE FUNCTION calculate_age_from_hetu(hetu CHAR(11))
RETURNS INT AS $$
DECLARE
    birthdate DATE;
    current_date DATE := CURRENT_DATE;
    age INT;
BEGIN
    birthdate := get_birthdate_from_hetu(hetu);
    
    age := EXTRACT(YEAR FROM current_date) - EXTRACT(YEAR FROM birthdate);

    -- Adjust age if the birthday hasn't occurred yet this year
    IF current_date < birthdate + age * INTERVAL '1 year' THEN
        age := age - 1;
    END IF;

    RETURN age;
END;
$$ LANGUAGE plpgsql IMMUTABLE;

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions