Announcement

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

  • Convert Integer Date to Date Format

    Hi all,
    I have a problem with converting an integer-type date (format %d) to long-type date (%10.0g), or vice versa. They just need to match such that I can create a new column that identifies when two dates match in two different columns or subtract one date column from the other and see when it is equal to 0.
    I need to convert an integer date i.e. 14jan1970 to a date format: 700114
    I have tried many different methods; however, the main issue is when converting the integer date to a number-type date, it becomes a 4-digit number. Unsure what to do here.
    I also tried the below code and it just gave a new column with missing values:

    tostring date, gen(datevar)
    gen date2 = date(datevar, "YYMMDD")
    format date2 %td

    Can someone please advise on how to convert the dates such that I can subtract one from the other and find == 0?
    Thank you all for your help!!

  • #2
    This is what I think you're asking for.

    Code:
    clear
    set obs 2
    gen indate = mdy(1, 14, 1970) in 1
    replace indate = mdy(2, 5, 2020) in 2
    format indate %td
    gen wanted = real(string(indate, "%tdYYNNDD"))
    list
    
         +--------------------+
         |    indate   wanted |
         |--------------------|
      1. | 14jan1970   700114 |
      2. | 05feb2020   200205 |
         +--------------------+
    The real() conversion may not be needed or a good idea.

    EDIT: In your example 14 January 1970 is underneath its date format an integer 3666. Convert that to string though you can, there is no way that the result of the way you did it maps onto a YYMMDD pattern. But you can get closer by using an appropriate display format.

    To understand dates and times, there is no short-cut beyond reading the documentation. I wish I could tell you otherwise.
    Last edited by Nick Cox; 05 Feb 2020, 04:23.

    Comment


    • #3
      Thank you for your help on this! The code actually worked perfectly for what I was looking for.

      Comment

      Working...
      X