Announcement

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

  • Extracting year from date variable

    Hello,

    My date variable looks like the following. I have tried using this command but it gives me a mismatch error.

    May I get the correct way to extract year from my date variable ?

    I used this code below to extract year and got the error

    Code:
    gen year=year(date) 
    type mismatch
    r(109);

    dataex date

    ----------------------- copy starting from the next line -----------------------
    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input str10 date
    "2000-11-29"
    "2000-11-29"
    "2000-12-01"
    "2000-11-29"
    "2000-12-01"
    "2000-12-01"
    end

  • #2
    Code:
    g year=substr(date,1,4)
    
    destring year, replace

    Comment


    • #3
      Thanks for your kind and quick response! I appreciate it !

      I have found another way to do it, in case if anyone wants to explore. But, Mr. Morlet's option is easier and faster.

      Code:
      gen sd3_date = date(date, "YMD")
      format sd3_date %td
      list sd3_date
      gen year=year(sd3_date)

      Comment


      • #4
        Both solutions can be telescoped.

        Code:
        gen year = real(substr(date,1,4))  
        
        gen year2 = year(daily(date, "YMD"))
        Last edited by Nick Cox; 23 Sep 2023, 09:07.

        Comment


        • #5
          Originally posted by Nick Cox View Post
          Both solutions can be telescoped.

          Code:
          gen year = real(substr(date,1,4))
          
          gen year2 = year(daily(date, "YMD"))
          Thanks for helping me me deep dive into this! appreciate the kind response !

          Comment

          Working...
          X