Converting from a numeric date to a date type in C# and RPG
Let's compare one of the most common and confusing tasks for all programmers - date conversion.
Given that this is such as a common programming task I am always surprised by how complex this is in many languages.
Here's our problem. Our iSeries legacy table 'Orders' is holding its order date not in the iSeries Date type but in numeric 8,0 in ISO format YYYYMMDD. e.g. ORDATE = 20081021
We need to convert this to a date type in RPG so that we can do some date work - adding a day on it subtracting order date from ship date etc.
RPG Code
Line 1 is the D-spec entry to define the converted date.
Line 2 defines the input order date (typically this comes from a db)
D OrderDateD S d datfmt(*iso)
D ORDATE S 8 0
OrderDateD = %date(ORDATE:*ISO);
// now we cand do some date work with OrderDateD!
Now lets do the same thing in C#
C# Code
Console.WriteLine("Method 2 - ParseExact Method a little simpler");
int ORDATE = 20081210;
DateTime OrderDateD = DateTime.ParseExact(ORDATE.ToString(), "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine("Date as numeric entered YYYYYMMDD {0}", OrderDateD);
In C# you use the ParseExact method to convert from YYYYMMDD or any other format.
1. Create a date type OderDate with the statement 'DateTime OrderDateD'
2. Assign it the value of ORDATE after parsing it first
The ParseExact method takes 3 parameters
a) The input date in whatever format but converted to a string. We use ToString to convert
b) The fomat of the input date which is specified here as YYYYMMDD. Click here for formats
c) The 'invariant' culture property to tell the method that this is a non standard format. How geeky!
There is another method called 'Parse' but ParseExact is used here because you can specify (in the second parm) the EXACT format that may not confom to any particular standard. This is really handy for handling obscue legacy stored dates in old iSeries tables.
The Parse method though is really clever so when you are using standard date formats it can automatically figue out your date format without telling it what format you are using.
I think its fair to say that the RPG approach is simpler and easier to understand. However there is more flexibility in the C# approach.
DOWNLOADS
See the C# code as a full project which shows both Parse and ParseExact
Also here's an RPG date cheat sheet code adapated from a post by Mitchel Laman
Which fomats to use when describing your input? Click here
Labels: C#, date, date conversion, parse method, parseexact, RPG
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home