Calculate age

Hello everyone,

I’m totally new with Natural and I made a PGM to calculate age but I have a Bug with move edited
The PGM is:

define data
LOCAL
1 AGE-CALCULATION
  2 NAME (A10)
  2 YOB (N4)
  2 DATE-CURRENT (D) INIT <*DATX>
  2 DATE-AGE (N10)
  2 OUTPUT (N4)
end-define

MOVE EDITED DATE-CURRENT (EM=YYYY) TO DATE-AGE

INPUT NAME 
INPUT YOB

COMPUTE OUTPUT := DATE-AGE - YOB

WRITE 'Hello' NAME 
WRITE 'You are' OUTPUT 'Years old'

END

The MOVE EDITED target must be an alpha field.

2 DATE-AGE-A (A4)    2 REDEFINE DATE-AGE-A
  3 DATE-AGE (N4)
MOVE EDITED DATE-CURRENT (EM=YYYY) TO DATE-AGE-A
2 Likes

I’ll point out that this only works if today is after the user’s birthday. I would write it:

DEFINE DATA LOCAL
1 TODAY    (N8)
1 REDEFINE TODAY 
  2 YYYY   (N4)
  2 MMDD   (N4)
1 DOB      (N8)
1 REDEFINE TODAY 
  2 YYYY   (N4)
  2 MMDD   (N4)
1 AGE (N4)
etc
END-DEFINE

MOVE *DATN TO TODAY
MOVE WORKER.DOB TO DOB  /* this assumes the worker.dob is N8 yyyymmdd.

AGE = TODAY.YYYY - DOB.YYYY
IF TODAY.MMDD LT DOB.MMDD
  SUBTRACT 1 FROM AGE
END-IF
2 Likes

OK so I know it’s not Friday when this kind of thing is usually brought up but, adding one more complication, in some cultures you are considered 1 on the day of birth rather than our 1 on the first anniversary of birth.

Let’s factor that into the intellectual exercise.

Mick Fitzpatrick
Expert Technology Consultant
o: 630-944-1154
c: 301-529-8022

2 Likes

Well Gentlemen many thanks for your support and quick replies.
This is the final version of my Code, in Order to share our knowledge

define data
LOCAL
1 AGE-CALCULATION
  2 NAME (A10)
  2 YOB (N4)
  2 DATE-CURRENT (D) INIT <*DATX>
  2 DATE-AGE (A10)
  2 REDEFINE DATE-AGE
    3 DATE-AGE-YYYY (N4)
  2 OUTPUT (N4)
end-define

MOVE EDITED DATE-CURRENT (EMU=YYYY) TO DATE-AGE

INPUT NAME YOB

IF SUBSTR (DATE-AGE,1,4) IS (N4)
  COMPUTE OUTPUT := DATE-AGE-YYYY - YOB
ELSE
  WRITE 'FEHLER'
END-IF

WRITE 'HELLO' NAME 
WRITE 'YOU ARE' OUTPUT 'YEARS OLD'


END
1 Like

Pretty good for a first program. In the interest of knowledge sharing:

  • The edit mask YYYY extracts 4 digits, so DATE-AGE should be defined as A4. If the IF statement was necessary (see below), you could eliminate the extra CPU for the SUBSTR clause.

  • *DATX is always a valid value, so DATE-CURRENT is always valid, and the edit mask YYYY will always extract 4 valid digits. The IF statement is unnecessary. It just wastes CPU.

  • Because Natural is an interpreted run-time, as a rule, we try to reduce the number of executable statements, for performance. (Of course the trade-off is legibility.) You could replace the third WRITE keyword with a slash (/).

/ 'YOU ARE' OUTPUT 'YEARS OLD'
2 Likes