Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Help with dates

    Hi I am new to this site so sorry if this is a very silly question or my problem is not well explained! I am trying to work with dates and can't find the answer in the documentation/other forums.

    I want to calculate age using two dates.

    I am using as an example code:
    . generate mat_age_birth = age(mat_birth_date, child_birthdate)

    However using my current dataset this code generates a new variable with all missing values. i.e. no error code but it says missing values generated.

    I think perhaps the issue is the way that the dates I am using are stored?? They are stored as double variables, format %tcDD-MON-CCYY
    I have tried to change the variable to either a string but with no success. I have tried to using "tostring", and "recast" to try to generate string variables - it comes back with "cannot be converted reversibly" so I think perhaps these are not appropriate for this particular issue?

    My question is
    1. can I calculate with dates while they are stored as "double" and if so how do I modify the above code to give me valid results
    2. if not, is it best to convert to string, and what is the code I would need to convert a double variable to string

    Thanks in advance and apologies if this is a silly question!

  • #2
    If you have your variables display formatted %tcDD-MON-CCYY and they read as possible real-life dates, then they are not date variables. They are clock variables, which are different animals altogether. The -age()- function only works with date variables. So you need to convert these clock variables to actual date variables. (Not to strings, which will not work with any of the Stata date manipulation functions!) So
    Code:
    foreach v of varlist mat_birth_date child_birthdate {
        gen date_`v' = dofc(`v')
        format date_`v' %tdDD-MON-CCYY
    }
    gen generate mat_age_birth = age(date_mat_birth_date, date_child_birthdate)
    By the way, it is OK for date variables to be stored as doubles (or as floats or even as ints). Clock variables, however, require -double- storage to retain precision.

    Comment


    • #3
      Thank you so much for your help - I have run this code and it has worked perfectly - am very grateful!

      Comment

      Working...
      X