Useful Utility App Class (PeopleCode) Methods

Sometimes we need to write our own methods or functions for data type conversions or separate certain repeated logic so that we can use them over and over again. This re-usability of code can be achieved via PeopleCode functions or using Application class methods. I personally like to use Application Classes to create these kind of common utility methods so that I can get the benefit of object-oriented programming. Below is an example of a Utility class which has few methods for data Type conversions. This class defines following methods;

1. String to Number conversion
2. String "YYYY-MM-DD" to date conversions
3. String "DD-MM-YYYY" to date conversion
4. String "YYYY-MM-DD" to Date conversion
5. DateTime to string conversion


/*Declare Class*/
class MyUtil
/* Type Conversions */
   method stringToNumber(&inString As string) Returns number;
   method stringToDate(&inString As string, &strFormat As string) Returns date;
   method stringToDateTime(&inString As string) Returns datetime;
   method datetimeToString(&inDatetime As datetime) Returns string;
end-class
 
/* String to Number conversion */
method stringToNumber
   /+ &inString as String +/
   /+ Returns Number +/
   
   Return Value(&inString)
end-method;

/* String "YYYY-MM-DD" or "DD-MM-YYYY" to Date conversion */
method stringToDate
   /+ &inString as String +/
   /+ &strFormat as String +/
   /+ Returns Date +/
   
   Local number &Year, &Month, &Day;
   Local date &date;
   
   If All(&inString) Then
   
    If &strFormat = "YYYY-MM-DD" Then
    
    &Year = Value(Substring(&inString, 1, 4));
    &Month = Value(Substring(&inString, 6, 2));
    &Day = Value(Substring(&inString, 9, 2));
    
    Return (Date3(&Year, &Month, &Day));
    End-If;
   
      If &strFormat = "DD-MM-YYYY" Then
    
    &Day = Value(Substring(&inString, 1, 2));
    &Month = Value(Substring(&inString, 4, 2));
    &Year = Value(Substring(&inString, 7, 4));
    
    Return (Date3(&Year, &Month, &Day));
    End-If;
 Else
      /* Return Null Date */
      Return &date;
   End-If;   
end-method;

/* String "YYYY-MM-DD" to DateTime conversion */
method stringToDateTime
   /+ &inString as String +/
   /+ Returns DateTime +/
   
   Local datetime &dateT;
   
   If All(&inString) Then
      Return (DateTimeValue(&inString));
   Else
      /* Return Null Date */
      Return &dateT;
   End-If;
   
end-method;

method datetimeToString
   /+ &inDatetime as DateTime +/
   /+ Returns String +/
   
   Local string &strDatetime;
   Local datetime &nullDatetime;
   
   If &inDatetime <> &nullDatetime Then
      &strDatetime = DateTimeToLocalizedString(&inDatetime, "MM/dd/yyyy HH:mm:ss");
      &strDatetime = &strDatetime | ".000000";
      Return &strDatetime;
   Else
      /* Return Null Date */
      Return "";
   End-If;
   
end-method;

SHARE

Ayesha Wee

    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment