UCLA Academic Technology Services HomeServicesClassesContactJobs

SPSS Code Fragment
Looping with dates

If date data have been entered as string variables and need to be converted into date variables, a macro can be used to do the conversion.  The macro below, called ddate, takes a list of string variables and a suffix as arguments to create date (numeric) versions of the inputted string variables.  In the example below, the string variables date1, date2 and date3, as well as the suffix _n, are supplied in the macro call.  The new date (numeric) variables date1_n, date2_n and date3_n are created.

data list list
/date1 (a10) date2 (a10) date3 (a10).
begin data.
06/12/2005 07/05/2006 03/05/2009
12/11/2003 11/10/2005 10/05/2006
04/06/2007 09/10/2004 10/10/2006
end data.

define ddate( vlist = !charend('/')
                               /suffix = !cmdend)

!do !vname !in (!vlist)
!let !nname = !concat(!vname, !suffix)

string m  (a2).
string d (a2).
string y (a4).
exe.
compute m = substr(!vname, 1, 2).
compute d = substr(!vname, 4, 2).
compute y = substr(!vname, 7, 4).

compute mn = numeric(m, f4.0).
compute dn = numeric(d, f4.0).
compute yn = numeric(y, f4.0).

compute !nname = date.dmy(dn, mn, yn).

formats !nname (date10).
exe.
delete variables m d y mn dn yn .

!doend
!enddefine.

ddate vlist = date1 date2 date3 
 /suffix = _n.
list.
date1      date2      date3         date1_n    date2_n    date3_n 
 
06/12/2005 07/05/2006 03/05/2009 12-JUN-05  05-JUL-06  05-MAR-09 
12/11/2003 11/10/2005 10/05/2006 11-DEC-03  10-NOV-05  05-OCT-06 
04/06/2007 09/10/2004 10/10/2006 06-APR-07  10-SEP-04  10-OCT-06 
 
Number of cases read:  3    Number of cases listed:  3

How to cite this page

Report an error on this page

UCLA Researchers are invited to our Statistical Consulting Services
We recommend others to our list of Other Resources for Statistical Computing Help
These pages are Copyrighted (c) by UCLA Academic Technology Services


The content of this web site should not be construed as an endorsement of any particular web site, book, or software product by the University of California.